/// <summary> /// 开启客户端socket /// </summary> public static void ClientSocketStarting(SocketConnectConfig sktconfig) { Sktconfig = sktconfig; if (ServerSocketEndPoint != null && (SocketClient == null || !SocketClient.Connected)) { SocketClient = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketClientConnection = new SocketConnectionReConnectClient(SocketClient); SocketClient.BeginConnect(ServerSocketEndPoint, ConnectCallback, SocketClientConnection); } }
private static void ConnectCallback(IAsyncResult ar) { try { //处理连接上之后的逻辑 //这个链接会在多次客户端请求的过程中重用,只会在第一次连接的时候调用,以后在不关闭通信窗口的时候不会重复调用 //RemoteEndPoint远程地址 LocalEndPoint本地地址 SocketConnectionReConnectClient handler = (SocketConnectionReConnectClient)ar.AsyncState; SocketClient.EndConnect(ar); LogMsg(handler.ConnectSocket.LocalEndPoint.ToString(), handler.ConnectSocket.RemoteEndPoint.ToString(), $"connect remote {handler.ConnectSocket.RemoteEndPoint}\r\n"); Sktconfig.ConnectCallback?.Invoke(handler); handler.ReceiveData(); } catch (SocketException sktex) { SocketException(SocketClient, sktex); SocketClient = null; SocketClientConnection = null; } catch (Exception ex) { Exception(ex); } }