如何在UWP c#中增加TCP连接头中的消息长度
本文关键字:消息 连接 增加 UWP TCP | 更新日期: 2023-09-27 18:16:53
我必须发送一个json消息到服务器与消息的长度,这个长度将被添加在头部。如:48 {jsondata}
public async void SendMessageToServer(string message)
{
try
{
ing len= message.Length;
using (writer = new DataWriter(socket.OutputStream))
{
writer.WriteString(message);
await writer.StoreAsync();
await writer.FlushAsync();
writer.DetachStream();
ReadResponse();
}
}
catch (Exception ex)
{
throw ex;
}
}
如果你想让它在消息之前作为文本,你就像写实际消息一样写它:
int len = message.Length;
using (writer = new DataWriter(socket.OutputStream))
{
writer.WriteString(len.ToString());
writer.WriteString(message);
...
然而,这感觉有点奇怪,因为服务器将不得不查找数字,直到它遇到一个非数字,然后读取它们。你确定是这样的吗?通常长度以二进制形式发送,例如32位长度为:
int len = message.Length;
using (writer = new DataWriter(socket.OutputStream))
{
writer.WriteInt32(len);
writer.WriteString(message);
...
我去解决方案长度将被添加为消息头,服务器总是读取消息长度的前5个字节。
using (DataWriter writer = new DataWriter(socket.OutputStream))
{
string len = String.Format("{0:D4}", message.Length);
writer.WriteString(len + "" + message);
await writer.StoreAsync();
await writer.FlushAsync();
writer.DetachStream();
}