private void ReadAvailable(TcpClient client) { Task.Run(() => { using (var s = client.GetStream()) { CommsEventArgs args = null; var data = _ReadPacketData(s); VarPacket p = null; try { p = VarPacket.CreateReceived(this, LocalEndPoint, data); } catch (ArgumentException ex) { args = new CommsEventArgs(p, client.Client.RemoteEndPoint as IPEndPoint, ex.Message); _listenerThread.Report(Tuple.Create(args, false, (VarPacket)null)); return; } args = new CommsEventArgs(p, client.Client.RemoteEndPoint as IPEndPoint, null); _listenerThread.Report(Tuple.Create(args, false, p.IsWriteRequest ? p : null)); if (p.IsReadRequest) { _RespondToRequest(p, client.Client.RemoteEndPoint as IPEndPoint, s); } } }); }
public void Send(VarPacket packet) { Task.Run(() => { CommsEventArgs args = null; try { using (var client = new TcpClient(packet.EndPoint.Address.ToString(), packet.EndPoint.Port) { NoDelay = this.NoDelay }) using (var s = client.GetStream()) { s.Write(packet.Data, 0, packet.Data.Length); s.Flush(); args = new CommsEventArgs(packet, LocalEndPoint, null); _listenerThread.Report(Tuple.Create(args, true, (VarPacket)null)); if (packet.IsReadRequest) { var data = _ReadPacketData(s); VarPacket p = null; try { p = VarPacket.CreateReceived(this, LocalEndPoint, data); } catch (ArgumentException ex) { args = new CommsEventArgs(p, client.Client.RemoteEndPoint as IPEndPoint, ex.Message); _listenerThread.Report(Tuple.Create(args, false, (VarPacket)null)); return; } args = new CommsEventArgs(p, client.Client.RemoteEndPoint as IPEndPoint, p.IsReadResponse ? null : "Wrong packet type received."); _listenerThread.Report(Tuple.Create(args, false, (VarPacket)null)); } } } catch (Exception ex) { args = new CommsEventArgs(packet, LocalEndPoint, ex.Message); _listenerThread.Report(Tuple.Create(args, true, (VarPacket)null)); } }); }