Event based TCP, IO/NIO and other questions

Hello
I’ve finished up a small server client library for myself. I’m only stuck with a couple of questions on how to improve it. At the moment i’m using normal IO for sockets instead of NIO. I looked NIO up and it varies a lot what people think about it. Some say it increases performance, others say it only increases performance on large file transfers and others say it doesnt increase performance at all, but rather makes it more scaleable. The only advantage that i can see is the non blocking write and reading. And it has a channel selection. However this isn’t very important on a game server i was thinking by myself, since i dont write a lot of data (positions, entity creations and entity actions mostly) and i have few clients (never more then 20). So would it make sense to rewrite the library and to make use of NIO?

Also secondly, as it is now i always have a ping of 3ms when localhosting, and i’m aware of the reason that causes this. Basically every connection is a thread in which is read and written. but since i dont actually dont do anything most of the time i added a Thread.sleep(1) call, just to give the application some rest (and not drain all the cpu). Is there any way to circumvent this? my loop on both the server and the client looks something along the lines of:


while(connected){
  if (inputStream.available() != 0) {read in packet}
  if (!packetsToSend.isEmpty()) {send a packet}
  Thread.sleep(1);
}

It works very well and i get a good connection to somebody from america (i’m from the NL) with an average ping of around 130. Of which i’m happy. But i like to improve it some more since sometimes there are some odd spikes.

And lastly i got another question. How to syncronize the connection and the game properly? As it is now i’m using libgdx and my own library. Whenever i get a packet that belongs to the game, i put it in an arraylist (and if not, i handle the packet right away). Then every update cycle of libgdx i read out the arraylist. something along the lines of:


while ((packet = client.getPacket()) != null) { check for the packet and execute the correct functions blabla}

where get.Packet() is:

return (connection == null) ? null : connection.getReceivedPacket();

and the getreceivedPacket is:

    public Packet getReceivedPacket() {
        if (receivedPackets.size() > 0) {
            Packet packet = receivedPackets.get(0);
            receivedPackets.remove(0);
            return packet;
        }
        return null;
    }

This solves multithreading problems quite well and i never get a problem doing this. I was just curious if there are other (better?) ways to handle this.

This must’ve been quite a read, i’m sorry for that! I’d highly appreciate it if somebody could help me out on one, or multiple, questions i’ve got!