hoyah_hayoh
hoyah_hayoh

Reputation: 85

Sockets to send many objects multiple times a second

So I have begun making a game that I would like to be multi player using sockets. It is a simple 2D game and all the objects I wish to send extend a class called Entity. I would like the positions of the objects to be sent at 30Hz with minimal delay or 'ping'. Currently I am sending the objects as an ArrayList which I am sure is not the best way to go about this, maybe I am wrong. Also, the code needs to allow for someone to join and send their player data (for example their name) without interfering with the ObjectInputStream that is expecting the locations rather than info. Here is what I have tried so far (Note that these are in a method that is called 30 times a second at regular intervals)

Client:

public void Update {
    ...
    outStream = new ObjectOutputStream(socket.getOutputStream());
    outStream.writeObject(w.getAllLocalEntities());
        //send objects created by this client (e.g bullets) and this client
    inStream = new ObjectInputStream(socket.getInputStream());
    w.setEntities((ArrayList<Entity>) inStream.readObject());
        //recieve all objects the server has recieved from all clients
}

Some objects are also created server side such as zombies etc. Server:

public void Update {
    ...
    inStream = new ObjectInputStream(socket.getInputStream());
    server.addEntities((ArrayList<Entity>) inStream.readObject());
        //recieve client objects
    outStream = new ObjectOutputStream(socket.getOutputStream());
    outStream.writeObject(server.getEntities());
        //send all objects
}

This seems to be very inefficient so I was wondering if anyone knows a better way of going about this. My main goal would be to Minimise latency/ping bearing in mind there can be a lot of objects (upwards of 500). So the question is... can you improve my method? Any help is appreciated.

Upvotes: 0

Views: 194

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Instead of sending data at 30Hz send data only when they changed.

Otherwise you risk to send many unmodified informations and you wait (at least few milliseconds) before sending new modified data.

Try to use an event driven paradigm: when a new event happens send the event to all the listeners.


Additionally don't send the whole object and don't use standard object serialization. If an object is composed with a fix part and a variable part (for example name and type can be fixed, location and power can change) send the whole data the first time and after send only the variable part. It saves lot of network traffic and cpu compsumption.

Upvotes: 1

Related Questions