Link to home
Start Free TrialLog in
Avatar of ee_lcpaa
ee_lcpaa

asked on

Winsock programming problem

Hi All,

I am writing a simple clinet/server program by using winsock.

If TCP is being used, is this truth that the recv function may be called twice sometimes in order to receive the whole packets sent by another side.

e.g A side is sending 2048 bytes, I may receive only 1000 bytes in my first call of the recv function. Then I receive the remaining 1048 bytes in another call of the recv function.

Is this truth?

Please advise. Thanks.
Avatar of grg99
grg99

Right.  

So you can't depend on TCP to define "chunks" for you.  

One simple way is to precede each of your chunks with their length.  The receiver just reads the length, then reads "length" more bytes.

Avatar of ee_lcpaa

ASKER

Hi grg99,

what is the reason?

Is the packet too large, it is divided into two pakcets & reassemble at the receive side later.
Please advise. Thanks
Because TCP is defined as being free to merge and split data as needed.   If you do a bunch of 1-byte writes, TCP typically buffers them up until it gets a good sized packet, then sends it all in one chunk.    Similarly if you write a huge buffer, TCP has to split the data into packets that the network can handle.  For example, Ethernet is limited to 1580 byte packets, the internet routers in general only guaranteed 520 bytes. (I think now 99% of them handle full-size ethernet packets, but the guarantee is only 520).

So you may get bigger or smaller chunks than you send.   Any chunking you want done you have to do yourself.  Luckily it's almost trivial, just send a length word in fornt of each chunk, then collect the right size chunk on the receiving end.

Hi grg99,

Do you mean the max. packet size is limited by the network equipments / physical wire usually?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of DarthMod
DarthMod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial