如何通过套接字发送ArrayList? (TCP)

时间:2015-09-13 23:14:07

标签: java tcp

我一直试图通过套接字将ArrayList发送到我的服务器。

public class Packet00Login extends Packet
{
private String username;
private double x, y;
private int dir;
private float health;

private List<Mob> mobs;

public Packet00Login(byte[] data)
{
    super(00);
    String[] dataArray = readData(data).split(",");
    this.username = dataArray[0];
    this.x = Double.parseDouble(dataArray[1]);
    this.y = Double.parseDouble(dataArray[2]);
    this.dir = Integer.parseInt(dataArray[3]);
    this.health = Float.parseFloat(dataArray[4]);

    // this is where my problem is, I don't know how to parse it
    this.mobs = dataArray[5];
}

public Packet00Login(String username, double x, double y, int dir, float health, List<Mob> mobs)
{
    super(00);
    this.username = username;
    this.x = x;
    this.y = y;
    this.dir = dir;
    this.health = health;

    this.mobs = mobs;
}

@Override
public void writeData(GameClient client)
{
    client.sendData(getData());
}

@Override
public void writeData(GameServer server)
{
    server.sendDataToAllClients(getData());
}

@Override
public byte[] getData()
{
    return ("00" + this.username + "," + this.x + "," + this.y + "," + this.dir + "," + this.health + "," + this.mobs).getBytes();
}

public String getUsername()
{
    return this.username;
}

public double getX()
{
    return this.x;
}

public double getY()
{
    return this.y;
}

public int getDir()
{
    return this.dir;
}

public float getHealth()
{
    return this.health;
}


public List<Mob> getMobs()
{
    return this.mobs;
}
 }

1 个答案:

答案 0 :(得分:0)

一种非常简单的方法是:使用GsonPacket00Login对象序列化为String对象并通过网络发送,然后在另一侧检索String对象和使用Gson将其反序列化为Packet00Login对象。