07-06-2006 10:59 AM
07-10-2006 08:34 AM
Martin is correct. You can not control the packet length at the lower transport levels. The protocols are free to combine or fragment your packets as they see fit for most efficient transport. As a result any call to receive a packet from a socket may have as few as 1 byte in it, or may have combined together multiple packets from the sender side.
The conventional solution to this is to check the incoming socket to see if there are bytes available and then move them to another buffer for holding until the entire packet has arrived. This is similar to how you would combine data from a serial port using an interrupt handler that gets called whenever data arrives at the UART. This can have benefits in that you create a FIFO buffer and just dump the received data into the buffer as it arrives at the socket port, and then your application can pull the packets out of the fifo buffer as needed. Of course there is a catch.
The implementation that microsoft uses for the socket stack makes it very difficult to determine if data is present without momentary blocking data input by the socket port. For very high performance systems (a lot of data in time critical transfer) calls to ioctlsocket() for FIONREAD under winsock 1.1 would slow down performance. The good news is that unless you are really pushing the socket interface hard, you can get away with this without much penalty. In a polled system, you can check the socket to see if any data is available and then move it to a ThreadSafeQueue as it comes in. The use of thread safe queues in this case is not to avoid thread issues, but to get access to a easy to implement FIFO data buffer.
You want to look at this link on MSDN for more detail on why this is sometimes viewed as a bad idea poll the socket interface for data present: http://support.microsoft.com/default.aspx?scid=kb;en-us;192599 but short of setting up your socket interface to callback into your application when data is available (similar to an interrupt handler) I do not know of another way to move large packets using the standard socket interface.
You may also find this link useful, it is a faq on basic winsock information:
http://tangentsoft.net/wskfaq/