jeudi 5 février 2015

Java Continuously read from active sockets


I'm basically programming a game server to use for a RPG game, I'm doing all within Java 8 and Socket.


So to the point; I am listening incoming connections from a single thread, if the connection is accepted I then add this connection to a Runnable class called " Communication " what this class does is loop through all existing connections to process more " incoming data / packets " as follows:



public void run() {
while (true) {
try {
Thread.sleep(100);
for (int i = 0; i < connections.size(); i++) {
try {
Connection connection = connections.get(i);

if (!connection.active) {
connections.remove(connection);
} else {
connection.listen();
}
} catch (IndexOutOfBoundsException e) {
continue;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


What the connection.listen method does is call "Socket.read" to read incoming packets/requests from the connected game client, this is the best way I've found to "asynchronously" listen to all active connections which might be up to 10~500


Is this a good way to process what I'm doing ? Is there a better way ? Should I extend Thread class to use with my Communication thread ? Is this "good code" to consider ?





Aucun commentaire:

Enregistrer un commentaire