2011-07-23 50 views
2

我發現這個API叫Kryonet。那麼,我試圖實現項目頁面中提供的示例。但是,這並不成功。Java Kryonet [類未註冊異常]

Server代碼:

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) 

什麼是錯的代碼?

回答

9

我以前從未聽說過Kryonet,但我假設您需要將kryo.register(...)行分別移至客戶端或服務器首次嘗試連接或接受連接之前。

+0

你知道這個庫的緩衝區溢出嗎?在我的Q中https://github.com/EsotericSoftware/kryonet/issues/134#issuecomment-333369190? –

1

Kryoserver是一個非常好的多線程客戶端 - 服務器管理器。

在連接客戶端並啓動或綁定到您的服務器之前,您必須註冊在客戶端和服務器上(以相同順序)發送和接收的所有類。

1

代碼順序應該是這樣的:

//創建服務器實例

Server服務器=新服務器();

//從服務器實例創建Kryo實例並註冊要通過網絡發送的類。

Kryo kryo = server.getKryo();

kryo.register(ClassNameYouWant.class);

//添加監聽

server.addListener(...);

//綁定端口

server.bind(4345);

//只有現在啓動服務器。

server.start();

在您的代碼中,您已經在註冊類和添加偵聽器之前啓動了服務器。