public void SendPacket(Packet packet) { int tries = 3; TcpClient client = null; while ((tries--) > 0) { try { client = new TcpClient(this.ip, this.port); NetworkStream networkStream = client.GetStream(); byte[] bytesToSend = ByteArrayParser.Serialize(packet); networkStream.Write(bytesToSend, 0, bytesToSend.Length); client.Close(); break; } catch { if (tries == 0) { Console.WriteLine("It's not possible to send message.. (tries=3)"); } if (client != null) { client.Close(); } } } }
public Packet ReceivePacket() { //---incoming client connected--- TcpClient client = listener.AcceptTcpClient(); //---get the incoming data through a network stream--- NetworkStream nwStream = client.GetStream(); byte[] buffer = new byte[client.ReceiveBufferSize]; int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); Packet message = ByteArrayParser.Deserialize <Packet>(buffer, bytesRead); nwStream.Close(); return(message); }