C#实现异步阻塞TCP(Send,Receive,Accept,Connect)
1.类
(1)服务器端操作类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | public class TcpServiceSocket { //接收数据事件 public Action<Socket, string > recvMessageEvent = null ; //发送结果事件 public Action< int > sendResultEvent = null ; //允许连接到tcp服务器的tcp客户端数量 private int numConnections = 0; //连接socket private Socket listenSocket = null ; //tcp服务器ip private string host = "" ; //tcp服务器端口 private int port = 0; //控制tcp客户端连接数量的信号量 private Semaphore maxNumberAcceptedClients = null ; private int bufferSize = 1024; private List<Socket> clientSockets = null ; public TcpServiceSocket( string host, int port, int numConnections) { if ( string .IsNullOrEmpty(host)) throw new ArgumentNullException( "host cannot be null" ); if (port < 1 || port > 65535) throw new ArgumentOutOfRangeException( "port is out of range" ); if (numConnections <= 0 || numConnections > int .MaxValue) throw new ArgumentOutOfRangeException( "_numConnections is out of range" ); this .host = host; this .port = port; this .numConnections = numConnections; clientSockets = new List<Socket>(); maxNumberAcceptedClients = new Semaphore(numConnections, numConnections); } public void Start() { try { listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind( new IPEndPoint(IPAddress.Parse(host), port)); listenSocket.Listen(numConnections); AcceptAsync(); } catch (Exception) { } } private async void AcceptAsync() { await Task.Run( new Action(() => { while ( true ) { maxNumberAcceptedClients.WaitOne(); try { Socket acceptSocket = listenSocket.Accept(); if (acceptSocket == null ) continue ; clientSockets.Add(acceptSocket); RecvAsync(acceptSocket); } catch (Exception) { maxNumberAcceptedClients.Release(); } } })); } private async void RecvAsync(Socket acceptSocket) { await Task.Run( new Action(() => { int len = 0; byte [] buffer = new byte [bufferSize]; try { while ((len = acceptSocket.Receive(buffer, bufferSize, SocketFlags.None)) > 0) { if (recvMessageEvent != null ) recvMessageEvent(acceptSocket, Encoding.UTF8.GetString(buffer, 0, len)); } } catch (Exception) { CloseClientSocket(acceptSocket); } })); } public async void SendAsync(Socket acceptSocket, string message) { await Task.Run( new Action(() => { int len = 0; byte [] buffer = Encoding.UTF8.GetBytes(message); try { if ((len = acceptSocket.Send(buffer, buffer.Length, SocketFlags.None)) > 0) { if (sendResultEvent != null ) sendResultEvent(len); } } catch (Exception) { CloseClientSocket(acceptSocket); } })); } public async void SendMessageToAllClientsAsync( string message) { await Task.Run( new Action(() => { foreach ( var socket in clientSockets) { SendAsync(socket, message); } })); } private void CloseClientSocket(Socket acceptSocket) { try { acceptSocket.Shutdown(SocketShutdown.Both); } catch { } try { acceptSocket.Close(); } catch { } maxNumberAcceptedClients.Release(); } public void CloseAllClientSocket(Socket acceptSocket) { try { foreach ( var socket in clientSockets) { socket.Shutdown(SocketShutdown.Both); } } catch { } try { foreach ( var socket in clientSockets) { socket.Close(); } } catch { } try { listenSocket.Shutdown(SocketShutdown.Both); } catch { } try { listenSocket.Close(); } catch { } try { maxNumberAcceptedClients.Release(clientSockets.Count); clientSockets.Clear(); } catch { } } } |
(2)客户端操作类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | public class TcpClientSocket { //接收数据事件 public Action< string > recvMessageEvent = null ; //发送结果事件 public Action< int > sendResultEvent = null ; //连接socket private Socket connectSocket = null ; //tcp服务器ip private string host = "" ; //tcp服务器端口 private int port = 0; private int bufferSize = 1024; public TcpClientSocket( string host, int port) { if ( string .IsNullOrEmpty(host)) throw new ArgumentNullException( "host cannot be null" ); if (port < 1 || port > 65535) throw new ArgumentOutOfRangeException( "port is out of range" ); this .host = host; this .port = port; } public void Start() { try { connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); connectSocket.Connect(host, port); RecvAsync(); } catch (Exception) { } } private async void RecvAsync() { await Task.Run( new Action(() => { int len = 0; byte [] buffer = new byte [bufferSize]; try { while ((len = connectSocket.Receive(buffer, bufferSize, SocketFlags.None)) > 0) { if (recvMessageEvent != null ) recvMessageEvent(Encoding.UTF8.GetString(buffer, 0, len)); } } catch (Exception) { Restart(); } })); } public async void SendAsync( string message) { await Task.Run( new Action(() => { int len = 0; byte [] buffer = Encoding.UTF8.GetBytes(message); try { if ((len = connectSocket.Send(buffer, buffer.Length, SocketFlags.None)) > 0) { if (sendResultEvent != null ) sendResultEvent(len); } } catch (Exception) { Restart(); } })); } public void CloseClientSocket() { try { connectSocket.Shutdown(SocketShutdown.Both); } catch { } try { connectSocket.Close(); } catch { } } public void Restart() { CloseClientSocket(); Start(); } } |
2.使用
(1)服务器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public partial class Form1 : Form { TcpServiceSocket tcpServiceSocket = null ; private readonly string ip = "192.168.172.142" ; private readonly int port = 8090; public Form1() { InitializeComponent(); tcpServiceSocket = new TcpServiceSocket(ip, port, 10); tcpServiceSocket.recvMessageEvent += new Action<Socket, string >(Recv); } private void Recv(Socket socket, string message) { this .BeginInvoke( new Action(() => { tbRecv.Text += message + "\r\n" ; })); } private void btnStart_Click( object sender, EventArgs e) { tcpServiceSocket.Start(); } private void btnSend_Click( object sender, EventArgs e) { string message = tbSend.Text.Trim(); if ( string .IsNullOrEmpty(message)) return ; tcpServiceSocket.SendMessageToAllClientsAsync(message); tbSend.Text = "" ; } } |
(2)客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public partial class Form1 : Form { private TcpClientSocket tcpClientSocket = null ; private readonly string ip = "192.168.172.142" ; private readonly int port = 8090; public Form1() { InitializeComponent(); tcpClientSocket = new TcpClientSocket(ip, port); tcpClientSocket.recvMessageEvent += new Action< string >(Recv); } private void Recv( string message) { this .BeginInvoke( new Action(() => { tbRecv.Text += message + "\r\n" ; })); } private void btnStart_Click( object sender, EventArgs e) { tcpClientSocket.Start(); } private void btnSend_Click( object sender, EventArgs e) { string message = tbSend.Text.Trim(); if ( string .IsNullOrEmpty(message)) return ; tcpClientSocket.SendAsync(message); tbSend.Text = "" ; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本