C# Socket通讯连接多个客户端,判断是否掉线
创建服务器端Service

1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 Socket socketsend; 8 //创建负责监听的Socket 9 Socket soceketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 10 Dictionary<string, Socket> dic_soceket = new Dictionary<string, Socket>(); 11 private void button1_Click(object sender, EventArgs e) 12 { 13 //获得当前程序的ip地址 14 IPAddress addr = IPAddress.Parse(textBox1.Text); 15 //获得当前程序的端口号 16 IPEndPoint endpoint = new IPEndPoint(addr, int.Parse(textBox2.Text)); 17 //服务器开启对当前程序的监听 18 soceketWatch.Bind(endpoint); 19 //创建监听队列,允许同时10个客户段排队 20 soceketWatch.Listen(10); 21 //显示监听信息 22 textBox3.AppendText("监听成功,等待客户端连接!" + "\r\n"); 23 //开启线程。不停监听有没有客户端连接过来; 24 //Accept()方法内部是一个循环,不停监听有没有客户端连接过来,soceketWatch连接上客户端后,就返回一个用于通信的socketsend 25 //定义的soceketWatch:用于监听有没有客户端连接的socket 26 //定义的socketsend:用于和客户端通信的socket 27 28 Task.Factory.StartNew(() => 29 { 30 while (true) 31 { 32 try 33 { 34 socketsend = soceketWatch.Accept(); //Accept是一个不停监听的循环 35 this.Invoke(new Action(() => { textBox3.AppendText(socketsend.RemoteEndPoint.ToString() + "连接成功!" + "\r\n"); })); 36 dic_soceket.Add(socketsend.RemoteEndPoint.ToString(), socketsend); 37 //comboBox1中添加新连上的客户端 38 this.Invoke(new Action(() => 39 { 40 comboBox1.Items.Add(socketsend.RemoteEndPoint.ToString()); 41 42 })); 43 //开启线程,不停监听客户端发来的信息; 44 //Receive()方法内部是一个循环,socketsend不停监听有没有消息发过来 45 Thread.Sleep(5); 46 Receive(socketsend); 47 } 48 catch (Exception ex) 49 { 50 MessageBox.Show(ex.ToString()); 51 } 52 } 53 }); 54 } 55 56 private void Receive(Socket socketsend) 57 { 58 Task.Factory.StartNew(() => 59 { 60 while (true) 61 { 62 try 63 { 64 if (socketsend.Poll(-1, SelectMode.SelectRead)) //判断socket是否掉线 65 { 66 byte[] buffer = new byte[1024 * 1024 * 5]; 67 int nRead = socketsend.Receive(buffer, SocketFlags.Peek); 68 int r = socketsend.Receive(buffer); //r代表实际接收到的有效字节数 69 if (nRead == 0) 70 { 71 this.Invoke(new Action(() => 72 { 73 textBox3.AppendText(socketsend.RemoteEndPoint.ToString() + "掉线" + "\r\n"); 74 comboBox1.Items.Remove(socketsend.RemoteEndPoint.ToString()); 75 if (comboBox1.Items.Count == 0) 76 { 77 comboBox1.Text = ""; 78 } 79 })); 80 return; 81 } 82 string s = Encoding.UTF8.GetString(buffer, 0, r); //将接收的字节转换为字符串 83 this.Invoke(new Action(() => { textBox3.AppendText(s + "\r\n"); })); 84 } 85 } 86 catch (Exception) 87 { 88 throw; 89 } 90 } 91 }); 92 } 93 private void button2_Click(object sender, EventArgs e) 94 { 95 //发送信号给客户端 96 byte[] buffer = Encoding.UTF8.GetBytes(textBox4.Text.Trim()); 97 dic_soceket[comboBox1.SelectedItem.ToString()].Send(buffer); 98 } 99 }
创建客户端Client

1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 Socket socketclient; 8 private void button1_Click(object sender, EventArgs e) 9 { 10 socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 11 IPAddress ip = IPAddress.Parse(textBox1.Text); 12 IPEndPoint port = new IPEndPoint(ip, int.Parse(textBox2.Text)); 13 socketclient.Connect(port); 14 textBox3.AppendText(socketclient.RemoteEndPoint.ToString() + "连接成功!" + "\r\n"); 15 Task.Factory.StartNew(() => 16 { 17 while(true) 18 { 19 try 20 { 21 byte[] buffer = new byte[1024 * 1024 * 5]; 22 int r = socketclient.Receive(buffer); 23 if (r == 0) 24 { return; } 25 string s = Encoding.UTF8.GetString(buffer, 0, r); 26 this.Invoke(new Action(() => { textBox3.AppendText(s + "\r\n"); })); 27 } 28 catch (Exception) 29 { 30 31 throw; 32 } 33 } 34 }); 35 } 36 37 private void button2_Click(object sender, EventArgs e) 38 { 39 byte[] buffer = Encoding.UTF8.GetBytes(textBox4.Text.Trim()); 40 socketclient.Send(buffer); 41 } 42 }
判断Socket是否掉线

1 if (socketsend.Poll(-1, SelectMode.SelectRead)) //判断socket是否掉线,socketsend是和客户端通信的socket 2 { 3 byte[] buffer = new byte[1024 * 1024 * 5]; 4 int nRead = socketsend.Receive(buffer, SocketFlags.Peek); // 5 int r = socketsend.Receive(buffer); //r代表实际接收到的有效字节数 6 if (nRead == 0) 7 { 8 this.Invoke(new Action(() => 9 { 10 textBox3.AppendText("掉线" + "\r\n"); 11 })); 12 return; 13 } 14 string s = Encoding.UTF8.GetString(buffer, 0, r); //将接收的字节转换为字符串 15 this.Invoke(new Action(() => { textBox3.AppendText(s + "\r\n"); })); //输出收到的信息 16 }
服务器端(Service)界面
客户端(Client)界面
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南