【发布时间】:2014-05-11 02:31:11
【问题描述】:
我在 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);
所以我的问题是,如何在同一个数据包中发送长度和数据,如何在客户端正确处理它?
【问题讨论】:
-
使用
BitConverter.GetBytes而不是ASCII.GetBytes(这样,int(data.Length.) 总是会得到 4 个字节)
标签: c# sockets windows-phone-8 tcp stream-socket-client