如何在UWP C#中的TCP连接中添加标头中的消息长度

时间:2016-11-07 17:11:38

标签: c# tcp uwp

我必须向具有消息长度的服务器发送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;
            }
        }

2 个答案:

答案 0 :(得分:1)

如果你想在消息之前将它作为文本,你只需在编写实际消息时编写它:

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

答案 1 :(得分:0)

我将解决方案长度添加为消息上的标题,服务器始终读取消息长度的前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();
}