Example: How to Packetize A TCP Stream

zhaozj2021-02-08  257

The following example code is designed to replace the recv () call. Recv_packet () differs by returning only when it has received a full packet, or has failed trying. This is only example code, for educational purposes. See below for more information on The Code's Design Limitations and Ways You Can Work Around Them.

The default packet size of 2 bytes is large enough to allow 64 KB packets. That's the size I use in my programs, but the code is flexible enough to allow any packet size you want, up to 4 bytes. Beyond that, you'll have to update the bit-shifting logic to be able to handle integers beyond 32 bits, or, if your compiler and platform support them, use 64-bit integers. Also, if you choose to use 1-byte length prefixes, you can simplify The Code Below Significant.

That Assumes That The Length Prefix Is Part of The Packet. That IS, IF you are sending 8 data bytes, a 2-byte length prefix will be "10" for this packet. It's not necessary to do it this way, but it Does make the code simpler.

RECV_PACKET.CPP

#include

#include

Static const INT prefix_size = 2;

Static char g_holding_buffer [1000];

Static int g_held_bytes = 0;

// Pass in the socket handle, a Pointer to a buffer large enough to hold

// the packet, and the size of this buffer. Returns the size of the

// packet recceived on success, or 0 on failure.

INT RECV_PACKET (socket SD, Char * P_out_buffer, int buffer_size)

{

INT BYTES_READ = 0;

INT packet_size;

Bool building_prefix = true;

Assert (buffer_size == sizeof (g_holding_buffer);

// Copy Any Data Remaining from Previous Call Into Output Buffer.

IF (g_held_bytes> 0) {

Assert (buffer_size> = g_held_bytes); Memcpy (p_out_buffer, g_holding_buffer, g_held_bytes);

BYTES_READ = g_held_bytes;

g_held_bytes = 0;

}

// read the packet

While (1) {

IF (building_prefix) {

IF (Bytes_Read> = prefix_size) {

Packet_size = 0;

For (int i = 0; i

Packet_size << = 8;

Packet_size | = p_out_buffer [i];

}

Building_prefix = false;

IF (packet_size> buffer_size) {

// Buffer's Too Small To Hold The Packet!

// Do Error Handling Here.

Return 0;

}

}

}

IF (! building_prefix& (bytes_read> = packet_size)) {

Break; // finished building packet

}

INT new_bytes_read = RECV (SD, P_OUT_Buffer Bytes_Read,

Buffer_size - bytes_read, 0);

IF (NEW_BYTES_READ == 0) || (new_bytes_read == Socket_ERROR)) {

Return 0; // do proper error Handling Here!

}

BYTES_READ = New_BYTES_READ;

}

// if anything is Left in The Read Buffer, Keep a Copy of IT

// for the next call.

g_held_bytes = bytes_read - packet_size;

Memcpy (g_holding_buffer, p_out_buffer packet_size, g_held_bytes);

Return packet_size;

}

There are several reasons not to use this code as-is in a real program. First, this code has no real error handling. Since every program handles errors differently, I've simply marked the places you need to add error handling code.

The second major problem is the global variables. They prevent you from using recv_packet () with more than one socket or with multiple threads. You can move them into a structure and pass an instance of that structure to recv_packet (). Or, you can wrap the function and all the data it needs up into a class. This would be a good start towards your own socket class library.Third, notice that the code checks that the holding buffer and the caller's buffer are the same size. If the callers 'buffer is larger than the holding buffer, the memcpy () call at the bottom of recv_packet () can overflow the holding buffer. If the holding buffer is larger than the callers' buffer and the recv () call returns enough bytes, the memcpy () call at the top of the function can overflow the callers' buffer. This is a symptom, rather than the problem itself. The actual problem is that the buffering logic is too simple to allow more complex usage patterns. This is good for educational Purposes, But Bad for Effic iency. The key feature of a better buffering mechanism would be giving recv_packet () access to additional memory, so that overflows would not be an issue. One way to do this would simply be to allow recv_packet () to allocate dynamic memory. Another would be to set up a large ring buffer. A related improvement would be if recv_packet () could return more than one packet per call, which would save all the shuffling that goes on in the current code when more than one packet gets read into the Of the high buffers.

The fourth problem is that the code does not scale well beyond 2-byte prefixes. If you use 3-byte prefixes, that demands up to a 16 megabyte buffer, and for 4-byte prefixes you'd need a 4 gigabyte buffer. If you find yourself needing to transmit such large messages and you can not split them up into smaller packets, you'll probably need to use some other buffering area than main memory. The right storage area to use for packet buffering will depend on your program , of course.the final proBLE That RECV_PACKET () is Only Usable with Blocking Sockets.

转载请注明原文地址:https://www.9cbs.com/read-2454.html

New Post(0)