gpt4 book ai didi

Java tcp 套接字没有正确接收

转载 作者:可可西里 更新时间:2023-11-01 02:57:49 25 4
gpt4 key购买 nike

嗨,让我直奔问题。我有一个大的 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();
}
}
}

谢谢,祝你有美好的一天。

最佳答案

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

你的意思是你有一个很大的 JSON 消息。数据包是网络协议(protocol)用来交换信息的东西。

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

除非您正在查看线路,否则您不会查看数据包。您正在查看从 TCP 连接一端获得的字节数。

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}

非常好。你有相同的字节。现在制作一个 JSON 解析器,找出消息结束的位置并对其进行解析。

Why does it split the packet or something when it comes to the client

它将消息拆分为数据包,因为这就是 TCP 将消息发送到另一端的方式。 TCP 不是消息协议(protocol),它不知道也不关心应用程序将什么视为消息——那是应用程序的工作。

and how i can i fix this anyway?

编写一个 JSON 解析器来找出消息的结束位置。您还没有实现任何代码来通过 TCP 接收 JSON,因此在您实现之前它不会起作用。

TL;DR:如果你想要一个应用层的消息协议(protocol),你需要实现一个。 TCP 不是一个。

关于Java tcp 套接字没有正确接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40048448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com