gpt4 book ai didi

java - Kryonet连接成功但收不到消息

转载 作者:行者123 更新时间:2023-12-01 23:49:02 27 4
gpt4 key购买 nike

您好,我正在使用 Kryonet 作为我正在开发的游戏的网络库。

我在服务器端有这个代码:

public class MyServer {
Kryo kryo;
Server server;
Connection connection;
public MyServer(){
server = new Server();
server.start();
try {
server.bind(59990, 59900);
} catch (IOException e) {
System.out.println("FATAL ERROR");
}

kryo = server.getKryo();
kryo.register(Message.class);

server.addListener(new Listener() {
public void received (Connection con, Message str) {
System.out.println("Message recieved from client to server");
Message m = (Message)str;
System.out.println(m.text);

}
public void connected(Connection con){
System.out.println("Hey, we are connected!");
connection = con;
con.sendTCP("HOLA CLIENTE!!");
}
public void disconnected(Connection con){
System.out.println(":( He is gone... he'll never come back..");
}
});

}

public void sendMessage(String tipoMensaje,String tipoTropa,String id){
connection.sendTCP(tipoMensaje+"-"+tipoTropa+"-"+id);
}

}

在客户端:

public class MyClient {
Client client;
Connection connection;
Kryo kryo;
public MyClient(){
client = new Client();
client.start();


try {
kryo = client.getKryo();
kryo.register(Message.class);

client.connect(5000, "10.211.55.3", 59990, 59900);
//sendMessage("fromclient","ee","ee");

client.addListener(new Listener() {
public void received (Connection con, String str) {
System.out.println(str);

System.out.println("Message recieved from server to client");
}
public void connected(Connection con){
System.out.println("Hey, we are connected!");
connection = con;
Message m = new Message();
m.text="eeep";
client.sendTCP(m);
}
public void disconnected(Connection con){
System.out.println(":( He is gone... he'll never come back..");
}
});


} catch (IOException e) {
System.out.println("Error while connecting");
}


}


public void sendMessage(String tipoMensaje,String tipoTropa,String id){
client.sendTCP(tipoMensaje+"-"+tipoTropa+"-"+id);
System.out.println("Message sent from client to server");

}
}

Message 只是一个包含字符串的类。当我尝试将客户端连接到服务器时,我收到“嘿,我们已连接!”消息,然后在服务器的命令行中显示“从客户端到服务器收到的消息”。但是,m.text(消息内容)没有打印,我不知道为什么。

提前致谢。

最佳答案

这是因为监听器中没有方法 public void returned (Connection con, String str) - 基本上,您的服务器永远不会调用它。这也是您应该使用 @Override 的原因 - 您一开始就不会遇到此问题。

String str替换为Object o。然后 - 检查您的对象是否实际上是一个 Message。如果是,则将其转换为 Message 并打印出其文本。您的方法应如下所示:

@Override
public void received(Connection connection, Object packet) {
if (packet instanceof Message) {
System.out.println(((Message) packet).text);
}
}

关于java - Kryonet连接成功但收不到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549202/

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