Jump to content
  • Advertisement
Sign in to follow this  

Non-blocking sockets in java.nio

This topic is 3787 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

    public void StartServer() throws IOException, InterruptedException {
        SelectionKey acceptKey = server.register(sel, SelectionKey.OP_ACCEPT);
        int numClients = 0;
        Player clients[] = new Player[CLIENTS_MAX];
        for (int i = 0; i < CLIENTS_MAX; i++)
            clients = new Player();
        while (true) {
            try {
                if (acceptKey.selector().selectNow() <= 0) {
                    Thread.sleep(0, 100);
                Thread.sleep(0, 100);
                Set readyKeys = sel.selectedKeys();
                Iterator it = readyKeys.iterator();

                while (it.hasNext()) {
                    SelectionKey key = (SelectionKey)it.next();
                    if (key.isAcceptable()) { // someone has connected
                        clients = AcceptClient(clients, numClients, key);
                    else if (key.isReadable()) { // we've got a new message, process it
                        ReadMessageFromNetwork(clients, numClients, key);
                } // while (it.hasNext())
                HandleAllFights(clients, numClients);
            catch (IOException e) {
                acceptKey = server.register(sel, SelectionKey.OP_ACCEPT);
        } // while (acceptKey.selector().select() > 0)
It's all OK until one of clients disconnects. Then I keep getting "Error" like 100 times a second and no one else can connect. How do I fix this? Thx

Share this post

Link to post
Share on other sites
Depends on HOW he disconnects and how things are handled on your end.

Proper disconnects are handled by recv() returning 0 (blocking or not). Improper disconnects return -1 on recv() and error other than EWOULDBLOCK.

I'm not sure how the overlaying java wrapper handles it, but you need to handle proper disconnects in some way and error disconnects too.

You don't handle them + you call the try block inside an endless while, and the catch part isn't breaking out.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!