简体   繁体   中英

Preventing split packets over TCP

I am writing a program that transfers files over the network using TCP sockets.

Now I noticed that when I send a packet in size for example 1024 bytes, I get them split on the other side.

By "split" I mean I get some packets as if they were a part of a whole packet.

I tried to reduce the packet size and the algorithm worked, when the packet size was immensely small (about 30 bytes per packet) thus the file transferred very slowly.

Is there anything I can do in order to prevent the splitting?

SOLVED:i switched the connection to be over UDP and since UDP is packet bounded it worked

There is not such thing in TCP.

TCP is a stream, what you write is what you get at the other end. This does not mean you get it the way it was written; TCP may break or group packets in order to do the jobs as effectively as possible. You can send 8 mega bytes packet in one write and TCP can break down into 10, 100 or 1000 packets, what you need to know is that at the other end you will get exactly 8 mega bytes no more no less.

In order to do a file transfer effectively you need to tell the receiver how many bytes you are going to send. The receiver may read it in one chunk or in 100 chunks but must keep track of the data it reads and how many bytes to read.

Because TCP is stream oriented, TCP will not transfer information of 'packet boundaries', like UDP and SCTP.

So you must add information of packet boundaries to TCP payload, if it is not there already. There are several ways to do it:

  • You can use a length field for indicating how many bytes the following packet contains.
  • Or there could be a reserved symbol for separating different packets.

In all ways, receiver must read TCP input stream again, if complete packet is not received.

You can control the TCP maximum segment size in some socket implementations. If you set it low enough, you can make the segment fit inside a single packet. The BSD Sockets API, which influenced almost every other implementation, has a setsockopt() function that lets you set various options on the socket. One of them, TCP_MAXSEG , controls the maximum segment size.

Unfortunately for you, the standard Java Socket class doesn't support this particular option.

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