/// <summary> /// 接收消息回调处理 /// </summary> /// <param name="e"></param> public void OnReceiveCompleted(SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { return; //判断消息的接收状态 } AsyncUserToken token = e.UserToken as AsyncUserToken; int lengthBuffer = e.BytesTransferred; //获取接收的字节长度 string ipAddress = token.UserSocket.RemoteEndPoint.ToString(); MessageFormat msg = new MessageFormat(); //如果接收的字节长度为0,则判断远端服务器关闭连接 if (lengthBuffer <= 0) { msg.msgStr = "远端服务器已经断开连接"; msg.ipStr = ipAddress; if (OnDisconnectEvent != null) { OnDisconnectEvent(msg); } CloseClientSocket(e); } else { byte[] receiveBuffer = e.Buffer; byte[] buffer = new byte[lengthBuffer]; Buffer.BlockCopy(receiveBuffer, 0, buffer, 0, lengthBuffer); msg.msgStr = Encoding.Unicode.GetString(buffer); msg.ipStr = ipAddress; bool willRaiseEvent = token.UserSocket.ReceiveAsync(e); //继续异步接收消息 if (!willRaiseEvent) { OnReceiveCompleted(e); } if (OnReceiveCompletedEvent != null) { OnReceiveCompletedEvent(msg); //调用UI方法处理 } } }
public DispatchMessage(ref MessageFormat msg, ref SocketServerManager ssm) { m_MessageFormart = msg; m_IPString = m_MessageFormart.ipStr; m_SocketManager = ssm; }
private void SendBackToClient(string msg) { MessageFormat mf = new MessageFormat(msg, m_MessageFormart.ipStr); m_SocketManager.OnSend(mf); }