我发现这个API名为Kryonet。好吧,我试图实现项目页面中提供的示例。但是,它没有成功。
服务器代码:
public class KryoTest {
public KryoTest() throws IOException {
Server server = new Server();
server.start();
server.bind(54555, 54777);
server.addListener(new Listener() {
public void received(Connection connection, Object object) {
if (object instanceof SomeRequest) {
SomeRequest request = (SomeRequest) object;
System.out.println(request.text);
SomeResponse response = new SomeResponse();
response.text = "Thanks!";
connection.sendTCP(response);
}
}
});
Kryo kryo = server.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
}
public static void main(String[] args) throws IOException {
new KryoTest();
}}
客户代码:
public class Kryoclient {
public Kryoclient() throws IOException {
Client client = new Client();
client.start();
client.connect(5000,"192.168.1.4", 54555, 54777);
SomeRequest request = new SomeRequest();
request.text = "Here is the request!";
client.sendTCP(request);
Kryo kryo = client.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
}
public static void main(String[] args) throws IOException {
new Kryoclient();
}
}
例外:
run:
00:00 INFO: Connecting: /192.168.1.4:54555/54777
00:00 INFO: [kryonet] Connection 1 connected: /192.168.1.4
Exception in thread "main" java.lang.IllegalArgumentException: Class is not registered: client.SomeRequest
at com.esotericsoftware.kryo.Kryo.getRegisteredClass(Kryo.java:319)
at com.esotericsoftware.kryo.Kryo.writeClass(Kryo.java:374)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:484)
at com.esotericsoftware.kryonet.TcpConnection.send(TcpConnection.java:196)
at com.esotericsoftware.kryonet.Connection.sendTCP(Connection.java:68)
at client.Kryoclient.<init>(Kryoclient.java:24)
at client.Kryoclient.main(Kryoclient.java:30)
这段代码有什么问题?
答案 0 :(得分:9)
我之前从未听说过Kryonet,但我认为你需要将kryo.register(...)
行移到客户端或服务器首先尝试连接或接受连接之前。< / p>
答案 1 :(得分:1)
Kryoserver是一个非常好的多线程客户端 - 服务器管理器。
在连接客户端并启动或绑定到服务器之前,您必须注册在客户端和服务器上发送和接收的所有类(按相同顺序)。
答案 2 :(得分:1)
代码顺序应为:
//创建服务器实例
服务器服务器=新服务器();
//从服务器实例创建Kryo实例并注册您将通过网络发送的类。
Kryo kryo = server.getKryo();
kryo.register(ClassNameYouWant.class);
//添加听众
server.addListener(...);
//绑定端口
server.bind(4345);
//现在才启动服务器。
server.start();
在您的代码中,您已经在注册类和添加侦听器之前启动了服务器。