简体   繁体   中英

Socket c# send and receive

in server/client program without multi-Client
when the server send two message like:

byte[] data = Encoding.Default.GetBytes("hello world1");
socket.Send(data1, 0, data.Length, 0);

byte[] data = Encoding.Default.GetBytes("hello world2");
socket.Send(data1, 0, data.Length, 0);

the Client received the two messages in one message like:

hello world1hello world2

but I want the client receive the 2 send in 2 received

please help me how to fix it ??? :(

Use a line separator like '\\n' and split incomming messages. With TCP you must be prepared for situations where packets are splitted up or joined.

If you used UDP, you could send separate packets.

These are some of your options

  1. You can use length prefixed message . Where you always send the length of the message for example in the first 4 bytes. The server would read the first four bytes and know the length and know how many remaining bytes are part of this message. It would know the next four bytes and so on and so forth.
  2. You can have a message demarker . For example if you know that your message will never have a particular bit pattern you can send it as a message demarker. As an example the server might always scan for a bit pattern 0,1,0,1,0,1 and know that the message has ended
  3. You can use a higher level framework WCF where the infrastructure handles it for you

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