多執行緒在網路程式設計中的應用
1.伺服器端程式
class Threadtcpserver
{
private Socket ss;
public Threadtcpserver()
{
IPAddress local = IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(local, 13000);
ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ss.Bind(iep); // 將套接字與本地終結點繫結
//在本地13000埠號上進行監聽
ss.Listen(20);
Console.WriteLine("等待客戶機進行連線......");
while (true)
{
Socket client = ss.Accept(); // 得到包含客戶端資訊的套接字
ClientThread newclient = new ClientThread(client); //建立訊息服務執行緒物件
//把ClientThread 類的ClientService方法委託給執行緒
Thread newthread = new Thread(new ThreadStart(newclient.ClientService));
newthread.Start(); // 啟動訊息服務執行緒
}
}
static void Main(string[] args)
{
Threadtcpserver instance = new Threadtcpserver();
}
}
class ClientThread //負責處理客戶端與伺服器端之間的通訊
{
public static int connections = 0; //connections變量表示連線數
public Socket service;
int i;
public ClientThread(Socket clientsocket)
{
this.service = clientsocket; //service物件接管對訊息的控制
}
public void ClientService()
{
String data = null;
byte[] bytes = new byte[1024];
if (service != null)
{
connections++;
}
Console.WriteLine("新客戶連線建立:{0} 個連線數", connections);
while ((i = service.Receive(bytes)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("收到的資料: {0}", data);
// 處理客戶端發來的訊息,這裡是轉化為大寫字母
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// 傳送一條應答訊息
service.Send(msg);
Console.WriteLine("傳送的資料: {0}", data);
}
//關閉套接字
service.Close();
connections--;
Console.WriteLine("客戶關閉連線:{0} 個連線數", connections);
}
}
2.客戶端程式
class multithreadclient
{
static void Main(string[] args)
{
Socket client;
byte[] buf = new byte[1024];
string input;
IPAddress local = IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(local, 13000);
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(iep);
}
catch (SocketException)
{
Console.WriteLine("無法連線到伺服器!");
return;
}
while (true)
{
//在控制檯上輸入一條訊息
input = Console.ReadLine();
//輸入exit,可以斷開與伺服器的連線
if (input == "exit")
{ break;}
client.Send(Encoding.ASCII.GetBytes(input));
//得到實際收到的位元組總數
int rec = client.Receive(buf);
Console.WriteLine(Encoding.ASCII.GetString(buf, 0, rec));
}
Console.WriteLine("斷開與伺服器的連線......");
client.Close();
}
}