简体   繁体   中英

How to add message length in header in TCP connection in UWP C#

I have to send a json message to servers with length of a message, and this length will be add in header. like :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;
            }
        }

If you want it as text before the message you just write it as you're writing the actual message:

int len = message.Length;
using (writer = new DataWriter(socket.OutputStream))
{
    writer.WriteString(len.ToString());
    writer.WriteString(message);
    ...

This however feels a bit weird since the server would have to look up numbers until it comes across a non-number and then read them. Are you sure this is how it works? Usually the length is sent as a binary, which for example as a 32bit length would be:

int len = message.Length;
using (writer = new DataWriter(socket.OutputStream))
{
    writer.WriteInt32(len);
    writer.WriteString(message);
    ...

I go the solution length will be added as header on message and server always read first 5 bytes for the message length.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM