Kapil Dave
Kapil Dave

Reputation: 126

Java Socket Packet Reading Overlapping

I am tring to read packets on a port which is receiving 4 consecutive packets.When i am tring to read that data using input stream some times data is overlapping.Means sometime next packet is merging with previous packets. Here is the process that i am following

1. For every connection opening a new socket and starting a thread.

//Open a port on server socket.
        //While new Socket
                //accept a socket connection.
                //Start a new thread for that socket.               



  2. After that in threads run method tring to get all four packets
       for(int i=0;i<4;i++)
        {
        InputStream inputDataStream=socket.getInputStream();
            //Than converting it to byte array.
        } 

When processing this byte arrays some times packet is overlapping with previous packet.How can i read all 4 packets without overlapping.

Upvotes: 0

Views: 726

Answers (1)

user207421
user207421

Reputation: 311048

I am tring to read packets on a port which is receiving 4 consecutive packets.

Not with TCP you aren't. TCP is a byte-stream protocol. There are no 'packets'.

When i am tring to read that data using input stream some times data is overlapping. Means sometime next packet is merging with previous packets.

That's entirely to be expected. That's how TCP works. There are no packets. No message boundaries. No correspondence guaranteed between the amount of data presented to write() and the amount of data read by read().

If you want messages, you have to implement them yourself, with e.g.:

  • a length word prefix
  • an application protocol such as type-length-value
  • a self-describing protocol such as Object Serialization, XML, etc.

Upvotes: 1

Related Questions