I have an asynchronous TCP socket server in C # that I created using the TcpListener / TcpClient covers for Socket. I am new to networking in general, so I did not know how TCP handles sent data and how it does not preserve message boundaries. After a little research, I think I came up with a lasting solution, but I wonder if anyone has any more tips for me.
Currently, the data I'm sending is the bytes [] of the serial object of the class using protobuf (Google data exchange library) https://code.google.com/p/protobuf/
After serializing my data and before sending it, I decided to add 4 Int32 bytes at the beginning of the byte array. My idea is that when a packet is sent to the server, it will analyze Int32, and then wait until it receives this number of bytes before doing anything with the data, otherwise just call BeginRead again.
Here is the code he worked with before writing data, and it seems to work fine, but I'm open to any performance suggestions:
public byte[] PackByteArrayForSending(byte[] data) {
I am a bit stuck on the server. I am reading the packetLength variable using Buffer.BlockCopy to copy the first 4 bytes and then BitConverter.ToInt32 to read the length I should get. I'm not sure if I should constantly read the input to a client-specific Stream object, or just use a while loop. Here is an example of the code that I have on the server:
NetworkStream networkStream = client.NetworkStream; int bytesRead = networkStream.EndRead(ar); if (bytesRead == 0) { Console.WriteLine("Got 0 bytes from {0}, marking as OFFLINE.", client.User.Username); RemoveClient(client); } Console.WriteLine("Received {0} bytes.", bytesRead);
Thanks for your time and advice, I look forward to learning more about this topic.
source share