0

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?

4

1 回答 1

0

处理此问题的常用技术是在数据前面加上数据的长度。例如,如果您想发送 100 个字节,请将数字 '100' 编码为一个四字节整数(或一个两字节整数……由您决定)并将其附加到缓冲区的前面。因此,您实际上将传输 104 个字节,前四个字节表示后面有 100 个字节。在接收端,您将读取前四个字节,这表明您需要再读取 100 个字节。说得通?

随着协议的发展,您可能会发现需要不同类型的消息。因此,除了四字节长度之外,您还可以添加一个四字节消息类型字段。这将向接收方指定正在传输什么类型的消息,长度指示该消息的长度。

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);
于 2014-05-10T18:02:10.193 回答