protected override void OnReceived(TPacket resp) { var task = AsyncFuture <TPacket> .Get(resp.Id); if (task != null && !task.IsCancelled) { base.OnReceived(resp); } AsyncFuture <TPacket> .OnCompleted(resp); }
public virtual AsyncFuture <TPacket> SendAsync(TPacket req, Action <IAsyncContext <TPacket> > callback) { Check.Require(req != null); Check.Require(Coding != null); var future = AsyncFuture <TPacket> .Get(callback); req.Id = future.Id; future.Packet = req; if (Socket == null || !Socket.Connected) { future.Exception = new NetException(SocketError.NotConnected); return(future); } if (!NetHelper.InternetConnectedState) { future.Exception = new NetException(SocketError.NotConnected); //OnExceptionFired(future.Exception); return(future); } var data = Coding.EncodePacket(req); int length = data.Length + Params.PacketSeparateFlag.Length; var bytes = new byte[length]; data.CopyTo(bytes, 0); Params.PacketSeparateFlag.CopyTo(bytes, data.Length); try { Log.Info("Send packet:" + req.ToString()); future.AsyncResult = Socket.BeginSend(bytes, 0, length, SocketFlags.None, ar => { try { Socket.EndSend(ar); //wait response packet future.Reset(); future.Wait(); } catch (SocketException ex) { future.Exception = new NetException(ex.SocketErrorCode); //OnExceptionFired(future.Exception); Close(); } catch (Exception ex) { future.Exception = new NetException(ex.Message, ex); //OnExceptionFired(future.Exception); Close(); } }, null); } catch (IOException ex) { future.Exception = new NetException(ex.Message, ex); //OnExceptionFired(future.Exception); Close(); } catch (SocketException ex) { future.Exception = new NetException(ex.SocketErrorCode); //OnExceptionFired(future.Exception); Close(); } catch (Exception ex) { future.Exception = new NetException(ex.Message, ex); //OnExceptionFired(future.Exception); } return(future); }