/// <summary> /// 异步接收客户端消息 /// </summary> /// <param name="ar"></param> private void ReceiveDataAsync(IAsyncResult ar) { Socket socketClient = ar.AsyncState as Socket; try { int readLength = socketClient.EndReceive(ar); if (readLength > 0) { RecevierEvent?.Invoke(receiveBuffer, socketClient.RemoteEndPoint); Array.Clear(receiveBuffer, 0, receiveBuffer.Length); socketClient.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveDataAsync, socketClient); } else { socketsDic.Remove(socketClient.RemoteEndPoint); clientConnectList.Remove(socketClient.RemoteEndPoint); ConnectChangeEvent?.Invoke(); } } catch (Exception ex) { socketsDic.Remove(socketClient.RemoteEndPoint); clientConnectList.Remove(socketClient.RemoteEndPoint); ErrInfoEvent?.Invoke(ex.Message); } }
/// <summary> /// 关闭TCP服务器 /// </summary> public void Close() { if (socketServer == null) { return; } TcpIsStart = false; foreach (var socketItem in socketsDic.Values) { try { socketItem.Shutdown(SocketShutdown.Both); } catch { } try { socketItem.Close(); } catch { } } try { socketServer.Shutdown(SocketShutdown.Both); } catch { } try { socketServer.Close(); } catch { } socketsDic.Clear(); clientConnectList.Clear(); ConnectChangeEvent?.Invoke(); }
/// <summary> /// 异步监听客户端 /// </summary> /// <param name="ar"></param> private void AcceptAsync(IAsyncResult ar) { try { Socket socket = (Socket)ar.AsyncState; socket.BeginAccept(AcceptAsync, socket); Socket socketClient = socket.EndAccept(ar); socketsDic.Add(socketClient.RemoteEndPoint, socketClient); clientConnectList.Add(socketClient.RemoteEndPoint); ConnectChangeEvent?.Invoke(); byte[] arrSendMsg = Encoding.UTF8.GetBytes("Connected Successfully!"); Send(arrSendMsg, socketClient.RemoteEndPoint); socketClient.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveDataAsync, socketClient); } catch (Exception ex) { ErrInfoEvent?.Invoke(ex.Message); } }