Kryonet在多次发送自定义对象后断开连接

时间:2014-09-28 14:59:35

标签: java networking kryonet

我正在使用KryoNet学习一些网络内容,我有这个问题,当我从服务器向客户端发送对象时,它发送它就好了,我可以读取它,但是当我再次发送它时,我得到了这个错误。

服务器:

server = new Server();
    Kryo kryo = server.getKryo();
    kryo.register(Command.class, new JavaSerializer());
    server.start();
    try {
        server.bind(54555, 54777);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

客户端:

client = new Client();
    Kryo kryo = client.getKryo();
    kryo.register(Command.class, new JavaSerializer());
    client.setKeepAliveTCP(2000);
    client.start();
    try {
        client.connect(5000, "192.168.1.5", 54555, 54777);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    client.addListener(new Listener() {
        public void connected(Connection connection){

        }
        public void received (Connection connection, Object object) {
            if(object instanceof Command){
                Command c = (Command) object;
                textField.setText(Integer.toString(c.getTime()));
            }
        }
     });

MyClass的:

public class Command implements Serializable{

private static final long serialVersionUID = 1L;
private int time;

public Command(int time) {
    setTime(time);
}

public int getTime() {
    return time;
}

public void setTime(int time) {
    this.time = time;
}

}

堆栈跟踪:

Exception in thread "Client" com.esotericsoftware.kryo.KryoException: Error during Java deserialization.
at com.esotericsoftware.kryo.serializers.JavaSerializer.create(JavaSerializer.java:42)
at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:758)
at com.esotericsoftware.kryonet.KryoSerialization.read(KryoSerialization.java:57)
at com.esotericsoftware.kryonet.TcpConnection.readObject(TcpConnection.java:137)
at com.esotericsoftware.kryonet.Client.update(Client.java:239)
at com.esotericsoftware.kryonet.Client.run(Client.java:317)
at java.lang.Thread.run(Unknown Source)




Caused by: java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at com.esotericsoftware.kryo.serializers.JavaSerializer.create(JavaSerializer.java:40)
... 6 more

1 个答案:

答案 0 :(得分:1)

您是否尝试使用收到的方法检查从服务器获取的值?

我认为可能是因为你正在实现Serializable接口,因此数据被序列化,当你试图将它从整数转换为String时,它会导致问题。

尝试反序列化您收到的数据,看看会发生什么。