TCP StreamSocket数据接收

时间:2014-05-10 17:44:00

标签: c# sockets windows-phone-8 tcp stream-socket-client

我在Windows上使用TCP套接字写了一个服务器 - 客户端通信,它运行正常,但现在我试图将客户端移植到Windows Phone,但我真的坚持数据接收。我正在使用StreamSocket,我需要知道数据的长度。例如:

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);

我尝试在服务器端执行此操作,但我不认为这是一个很好的解决方案:

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);

所以我的问题是,如何在同一个数据包中发送长度和数据,以及如何在客户端正确处理它?<​​/ p>

1 个答案:

答案 0 :(得分:0)

处理此问题的常用技术是在数据前加上数据长度。例如,如果要发送100个字节,请对数字&#39; 100&#39;进行编码。作为一个四字节整数(或两个字节的整数...由你决定)并将其固定在缓冲区的前面。因此,您实际上将传输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);