C#网络通信(2)--TCP编程和多线程

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); } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值