【问题标题】:TCP StreamSocket data receivingTCP StreamSocket 数据接收
【发布时间】: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


【解决方案1】:

处理这个问题的常用技术是在数据前面加上数据的长度。例如,如果您想发送 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);

【讨论】:

  • 感谢您的出色回答,但我不太明白您的意思。我知道我的英语不太好,对此感到抱歉,但您能否提供一个示例代码来说明您的想法?
  • @David,添加了一些代码来用数据编码长度并发送它。希望这会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
  • 2010-12-10
  • 1970-01-01
  • 2013-01-20
相关资源
最近更新 更多