C# streaming sockets, how to separate messages?

后端 未结 6 1596
谎友^
谎友^ 2021-01-15 06:40

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:32

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

提交回复
热议问题