TCP服务器端使用多线程的基本思路:
监听并且启动线程:
IPAddress local = IPAddress.Any; IPEndPoint iep = new IPEndPoint(local, 13000); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 将套接字与本地终结点绑定 server.Bind(iep); //在本地13000端口号上进行监听 server.Listen(20); Console.WriteLine("等待客户机进行连接......"); while (true) { // 得到包含客户端信息的套接字 Socket client = server.Accept(); //创建消息服务线程对象 ClientThread newclient = new ClientThread(client); //把ClientThread 类的ClientService方法委托给线程 Thread newthread = new Thread(new ThreadStart(newclient.ClientService)); // 启动消息服务线程 newthread.Start();
在线程中获得内容:
class ClientThread { //connections变量表示连接数 public static int connections = 0; public Socket service; int i; public ClientThread(Socket clientsocket) { //service对象接管对消息的控制 this.service = clientsocket; } 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); } }