/// <summary> /// 开启客户端socket /// </summary> public static void ClientSocketStarting(SocketConnectConfig sktconfig) { if (ServerSocketEndPoint != null) { Sktconfig = sktconfig; SocketClient = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketClientConnection = new SocketConnectionClient(SocketClient); SocketClient.BeginConnect(ServerSocketEndPoint, ConnectCallback, SocketClientConnection); } }
/// <summary> /// 开启服务端socket监听 /// </summary> public static void ServerSocketListing(SocketConnectConfig sktconfig) { DicSockectConnection.Clear(); _cancellationTocken = new CancellationTokenSource(); if (sktconfig == null) { sktconfig = new SocketConnectConfig() { ServerSocket = ServerSocketListenner } } ; else if (sktconfig.ServerSocket == null) { sktconfig.ServerSocket = ServerSocketListenner; } Sktconfig = sktconfig; try { if (SocketConnectionClient.SocketClient != null && SocketConnectionClient.SocketClient.Connected) { SocketConnectionClient.SocketClientConnection.Disconnect(); } SocketConnectionClient.ClientSocketStarting(connection => { ServerSocketClient = (SocketConnection)connection; SendCurrentConnectionCount(); } //监听打开后,发送当前上位机的连接数目信息 ); ServerSocketListenner.IOControl(IOControlCode.KeepAliveValues, KeepAlive(1, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000), null); //设置心跳检测 ServerSocketListenner.BeginAccept(AcceptCallback, sktconfig); Task.Run(() => //解决主线程直接调用报错 { ShowMsg($"socket server listening at {ServerSocketListenner.LocalEndPoint}..."); }); } catch (SocketException se) { SocketException(ServerSocketListenner, se); } }
private static void ConnectCallback(IAsyncResult ar) { try { //处理连接上之后的逻辑 //这个链接会在多次客户端请求的过程中重用,只会在第一次连接的时候调用,以后在不关闭通信窗口的时候不会重复调用 //RemoteEndPoint远程地址 LocalEndPoint本地地址 SocketConnectionClient handler = (SocketConnectionClient)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); } }