嗨,让我直接解决问题。我有一次在客户端进行身份验证Java tcp socket无法正常接收
但包回来以一种不可思议的方式,喜欢它的分裂或东西例如服务器发送给该客户一个很大的JSON数据包:
的JSON应该是:
Received: {"UserID":1,"PlayerID":2,"EXP":0,"Lvl":1,"Coins":0,"ItemSlots":30}
当谈到过:
Received: {"UserID":1,"PlayerID":2,"EXP":0,"Lvl":1,"Coins":0,
Received: "ItemSlots":30}
为什么当它涉及到客户端它拆分包或东西,我怎么能解决这个问题呢?
的Java接收代码:
private class ClientThread extends Thread {
public void run() {
try {
while (selector.select() > 0) {
for (SelectionKey sk : selector.selectedKeys()) {
selector.selectedKeys().remove(sk);
if (sk.isReadable()) {
SocketChannel sc = (SocketChannel)sk.channel();
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
while (sc.read(buff) > 0) {
sc.read(buff);
buff.flip();
content += charset.decode(buff);
buff.clear();
}
System.out.println("Recieved: " + content);
sk.interestOps(SelectionKey.OP_READ);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
感谢有一个美好的一天。
尝试将ByteBuffer大小增加到2048. –
我试过它的工作,但不适用于大数据包,我猜想某些代码需要完成更大的数据包。 – Premt
试试这个:ByteBuffer.allocate(2048);在你的代码中 –