Premt Premt - 1 year ago 57
Java Question

Java tcp socket does not recieve properly

Hi lemme get straight to the problem so i got a big JSON packet that the server sends to this client once the client is authenticated

But the packet comes back in a weird way like its split or something example:

The JSON should be:

Recieved: {"UserID":1,"PlayerID":2,"EXP":0,"Lvl":1,"Coins":0,"ItemSlots":30}

When it comes through:

Recieved: {"UserID":1,"PlayerID":2,"EXP":0,"Lvl":1,"Coins":0,
Recieved: "ItemSlots":30}

Why does it split the packet or something when it comes to the client and how i can i fix this anyway?

Java Receive Code:

private class ClientThread extends Thread {
public void run() {
try {
while ( > 0) {
for (SelectionKey sk : selector.selectedKeys()) {

if (sk.isReadable()) {

SocketChannel sc = (SocketChannel);
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";

while ( > 0) {;
content += charset.decode(buff);

System.out.println("Recieved: " + content);
} catch (IOException e) {

Thanks have a wonderful day.

Answer Source

TCP protocol does not maintain message boundaries. It is not guaranteed that what the server sends is received as-is by the client and vice-versa.

If the server sends 1000 bytes data, the client application can receive the same across multiple recv or single recv. TCP does not guarantee any behaviour. "Split" can happen, it is upto the application to handle the data coming in multiple chunks, coalesce it to one unit of application data for further processing. One can see this particularly with large data sizes.