Thomas Banderas
Thomas Banderas

Reputation: 1739

Sync read and write

I'm using read and write functions to communicate between client and server.

If server use two times write, in Wireshark I can see that two packets was send, but my read function concat two packets in one buffer

Question: It is possible to my read function read only one payload at one time? I dont want reduce buffer

Ex: Situation now:

Send(8bytes) Send(8bytes)

Read, read 16 bytes

I want

Send(8 bytes) Send(8Bytes)

Read, read 8 bytes(first packet)

Read, read 8 bytes(second packet)

Upvotes: 1

Views: 880

Answers (2)

nafets mixy
nafets mixy

Reputation: 15

If you want to synchronize server and client use something like semaphores or you can send read/write bytes and this avoid sending information before client read it. Or if you know exactly length of message you can separate readed bytes. If you make buffer exact length of message remain bytes will be lost so make a server sending information when reader read previous message or extend buffer and separate multiple messages.

Upvotes: 0

janm
janm

Reputation: 18339

TCP/IP gives you an ordered byte stream. Reads and writes are not guaranteed to have the same boundaries, as you have seen.

To see where messages begin and end, you need to add extra information to your protocol to provide this information. A workable simple approach is to have a byte count at the start of each message. Read the byte count, then you know how many more bytes to read to get the complete message and none of the next message.

Upvotes: 3

Related Questions