Static Encoding encoding = Encoding.UTF8 Let us see this in practice by defining the 2 methods we listed above: While on the sender side, the rest of the message will be appended after the first 4 bytes. Once the message length is received, the buffer can be sized accordingly and the rest of the message stream be read. Thus we are setting that all messages would at least be 4 bytes in length so that the other party can be assured that they can safely read 4 bytes to get the message length. Let us say that the first 4 bytes (32 bits) would contain the length of the message. Since both server and client are our own, we can device our own protocol to send content length data. Therefore, we need to device a way of letting the other party know what is the message length so the other party can accordingly set the buffer size. But that would be sub optimal way as it increases the reading time and thus the communication time. Now buffer can be fixed to a size bigger than the longest message we expect to receive. We would prefer the later and for that we need to have a buffer. To read from the stream, we either need to read byte by byte or we can read the entire message in one go. streamToMessage: to read message from the stream and convert it to a string message.īut before we do that, we need to turn our attention to the content length of the message.messageToByteArray: to convert our message string into a byte array that can be written on the network stream.In both server and in the client side, we are yet to implement 2 methods namely: TcpListener listener = new TcpListener(ep) Ĭonsole.WriteLine("Server listening on: IPEndPoint ep = new IPEndPoint(ipAddr, port) As soon as we receive a new message on the listener, we process that and send the appropriate response. Since the program must never terminate and should keep listening, we will use an infinite while loop. We will create a TCP endpoint and then a TCP listener that keeps listening on the endpoint. In this article we will see how we can develop our own TCP client and server. It could be faster and consumes less memory as you will tailor it to your own needs and constraints.Lets you really optimize the communication at every bit level.If you wish to develop your own application protocol for server/client communication.Come in handy when all other application layer protocols like HTTP, FTP etc doesn’t suit your needs.If you want two network devices to talk to each other, then developing a TCP server and client is as low as you can get without blowing your brains off.