Question

I wrote a server-client communication with TCP sockets on Windows and it works properly, but now i'm trying to port the client-side to Windows Phone, but I'm really stuck at data receiving. I'm using StreamSocket and with that I need to know the length of the data. For example:

DataReader dataReader = new DataReader(clientSocket.InputStream);

uint bytesRead = 0;

bytesRead = await dataReader.LoadAsync(SizeOfTheData); // Here i should write the size of data, but how can I get it? 

if (bytesRead == 0)
    return;

byte[] data = new byte[bytesRead];

dataReader.ReadBytes(data);

I tried to do this on server-side, but I don't think this is a good solution:

byte[] data = SomeData();

byte[] length = System.Text.Encoding.ASCII.GetBytes(data.Length.ToString());

// Send the length of the data
serverSocket.Send(length);
// Send the data
serverSocket.Send(data);

So my question is, how can I send the length and the data in the same packet, and how can I properly process it on client-side?

Was it helpful?

Solution

A common technique for dealing with this is to prepend the data with the length of the data. For example, if you want to send 100 bytes, encode the number '100' as a four-byte integer (or a two-byte integer...up to you) and tack it onto the front of your buffer. Thus, you would actually transmit 104 bytes with the first four bytes indicating that there are 100 bytes to follow. On the receive side, you would read the first four bytes, which would indicate you need to read an additional 100 bytes. Make sense?

As your protocol advances, you may find that you need different types of messages. So in addition to a four-byte length, you might add a four-byte message type field. This would specify to the receive what type of message is being transmitted with the length indicating how long that message is.

byte[] data   = SomeData();
byte[] length = System.BitConverter.GetBytes(data.Length);
byte[] buffer = new byte[data.Length + length.Length];
int offset = 0;

// Encode the length into the buffer.
System.Buffer.BlockCopy(length, 0, buffer, offset, length.Length);
offset += length.Length;

// Encode the data into the buffer.
System.Buffer.BlockCopy(data, 0, buffer, offset, data.Length);
offset += data.Length;  // included only for symmetry

// Initialize your socket connection.
System.Net.Sockets.TcpClient client = new ...;

// Get the stream.
System.Net.Sockets.NetworkStream stream = client.GetStream();

// Send your data.
stream.Write(buffer, 0, buffer.Length);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top