C# streaming sockets, how to separate messages?

后端 未结 6 1193
情歌与酒
情歌与酒 2021-01-15 06:39

Kinda long title, but anyways...

I\'ve been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams

6条回答
  •  青春惊慌失措
    2021-01-15 07:23

    I guess this should do that: (I assume your data is a string)

    Stream stream = tcpClient.GetStream();
    Encoding encoding = Encoding.GetEncoding("encoding name");
    
    byte[] bytes = encoding.getBytes(data);
    
    stream.Write(BitConverter.GetBytes((short)bytes.Length),0,2); // hope data isn't longer that 64k
    stream.Write(bytes,0,bytes.Length);
    

提交回复
热议问题