private void OnReceive(Packet pk, IPEndPoint remote) { var e = new ReceivedEventArgs(pk); e.UserState = remote; LastTime = DateTime.Now; //if (StatReceive != null) StatReceive.Increment(e.Length); if (Log.Enable && LogReceive) { WriteLog("Recv [{0}]: {1}", e.Length, e.ToHex(32, null)); } Received?.Invoke(this, e); if (Packet != null && e.Packet != null && MessageReceived != null) { var msg = Packet.LoadMessage(e.Packet); var me = new MessageEventArgs { Packet = e.Packet, UserState = e.UserState, Message = msg }; MessageReceived(this, me); } }
/// <summary>发送消息并等待响应</summary> /// <param name="msg"></param> /// <returns></returns> public virtual async Task <IMessage> SendAsync(IMessage msg) { if (msg == null) { throw new ArgumentNullException(nameof(msg)); } var pk = new Packet(msg.ToArray()); if (Packet == null) { Packet = new PacketProvider(); } var task = msg.Reply ? null : Packet.Add(pk, Remote.EndPoint, Timeout); if (!SendByQueue(pk, Remote.EndPoint)) { return(null); } // 如果是响应包,直接返回不等待 if (msg.Reply) { return(null); } return(Packet.LoadMessage(await task.ConfigureAwait(false))); }