Skip to content

2.ByteMessageTcpClient ‐ Server

ReferenceType edited this page Jul 15, 2024 · 3 revisions

ByteMessageTcpClient/Server

It is build on top of AsyncTcpClient/Server, where only difference is messages are sent with 4 byte length header. This allows us to send messages with any length without fragmentation.

For detailed info on underlying system, please refer AsyncTcpClient/Server

  • Byte fragmentation occurs when message size exceeds max MTU. Which is around 1500 bytes and can be lower(depends..).
  • Each receiver unit on server and client side has stateful message extractor, where full messages are extracted from fragmented bytes by using length info.
  • Messages are guaranteed to reach destination atomically without fragmentation(As long as the connection is alive).

Example

ByteMessageTcpServer server = new ByteMessageTcpServer(20008);
server.OnBytesReceived += ServerBytesReceived;
server.StartServer();

ByteMessageTcpClient client = new ByteMessageTcpClient();
client.OnBytesReceived += ClientBytesReceived;
client.Connect("127.0.0.1", 20008);
client.SendAsync(Encoding.UTF8.GetBytes("Hello I'm a client!"));

void ServerBytesReceived(Guid clientId, byte[] bytes, int offset, int count)
{
    Console.WriteLine(Encoding.UTF8.GetString(bytes, offset, count));
    server.SendBytesToClient(clientId, Encoding.UTF8.GetBytes("Hello I'm the server"));
}

void ClientBytesReceived(byte[] bytes, int offset, int count)
{
    Console.WriteLine(Encoding.UTF8.GetString(bytes, offset, count));
}
Clone this wiki locally