如何为Array<>?编写序列化器

时间:2014-12-09 13:43:00

标签: java libgdx kryonet

我不知道如何处理这个问题。我需要为libgdx中的Array<>对象编写一个序列化器。

public static void initialize(Server server) {
    Kryo kryo = server.getKryo();
    kryo.register(ServerData.class);
    kryo.register(PlayerNick.class);
    kryo.register(MoveLeft.class);
    kryo.register(MoveRight.class);
    kryo.register(MoveUp.class);
    kryo.register(MoveDown.class);
    kryo.register(StandUp.class);
    kryo.register(ButtonLeft.class);
    kryo.register(ButtonRight.class);  
    //
    kryo.register(PlayerData.class);  
    kryo.register(Vector2.class);
    kryo.register(Array.class);  
    kryo.register(PlayerDataPacket.class);  
}
public static void initialize(Client client) {
    Kryo kryo = client.getKryo();
    kryo.register(ServerData.class);
    kryo.register(PlayerNick.class);
    kryo.register(MoveLeft.class);
    kryo.register(MoveRight.class);
    kryo.register(MoveUp.class);
    kryo.register(MoveDown.class);
    kryo.register(StandUp.class);
    kryo.register(ButtonLeft.class);
    kryo.register(ButtonRight.class); 
    //
    kryo.register(PlayerData.class);  
    kryo.register(Vector2.class);
    kryo.register(Array.class);  
    kryo.register(PlayerDataPacket.class);  
}
public static class PlayerData {
    public String name;
    public int id;
    public Vector2 position;
}

public static class PlayerDataPacket {
    public Array<PlayerData> playerList = new Array<PlayerData>();
}

这是我常规序列化的完成方式。在这里,我需要为PlayerDataPacket编写自定义序列化程序。

我找到了这个:https://groups.google.com/forum/#!topic/kryonet-users/9z4Ix2JO7JA 但它似乎已经过时,因为它找不到一些方法,而且它没有说明如何用Array<>来做。

1 个答案:

答案 0 :(得分:1)

我写了一个使用KryoNet在网络上发送浮点数组的例子:

https://stackoverflow.com/a/24339801/2413303

 Server server = new Server();
  Kryo kryo = server.getKryo();
  kryo.register(float[].class);
  server.start();
  server.bind(2300, 2301);
  server.addListener(new Listener() {
   public void received(Connection connection, Object object)
   {
      if(object instanceof float[])
      {
        float[] array = (float[])object;
        for(int i = 0; i < array.length; i++)
        {
           System.out.println("" + array[i]);
        }
      }        
   }});
  Client client = new Client();
  Kryo kryo = client.getKryo();
  kryo.register(float[].class);
  client.addListener(new Listener() {
    public void connected(Connection connection)
    {
       connection.sendTCP(new float[] {5, 6, 7, 8});
    }
  };
  client.connect(5000, "127.0.0.1”, 2300, 2301);