Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7654721
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T12:19:44+00:00 2026-05-31T12:19:44+00:00

I’m new with Java NIO, after reading some tutorials, I’ve tried my own to

  • 0

I’m new with Java NIO, after reading some tutorials, I’ve tried my own to write a simple NIO server and client.
My server just does a simple thing is listen from client and print to console, and the client just connects to server and send to it 3 messages “Hello”.
The problem is my server listens and works well with the 3 messages, after that it should be blocked and continue listening, but it does not, there’s no blocking, it runs it while loop infinitely. Here’s my server and client:

Server

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.Set;

public class Server {
    public static void main(String args[]) throws Exception {
        // Create the server socket channel
        ServerSocketChannel server = ServerSocketChannel.open();
        // nonblocking I/O
        server.configureBlocking(false);
        // host-port 8000
        server.socket().bind(new InetSocketAddress(8000));
        System.out.println("Server actives at port 8000");
        // Create the selector
        Selector selector = Selector.open();
        // Recording server to selector (type OP_ACCEPT)
        server.register(selector, SelectionKey.OP_ACCEPT);

        while (selector.select() > 0) {

            // Get keys
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> i = keys.iterator();

            // print 
            System.out.println("[ " + keys.size() + " ]");

            // For each keys...
            while (i.hasNext()) {
                SelectionKey key = (SelectionKey) i.next();
                // Remove the current key
                i.remove();

                // if isAccetable = true
                // then a client required a connection
                if (key.isAcceptable()) {
                    // get client socket channel
                    SocketChannel client = server.accept();
                    // Non Blocking I/O
                    client.configureBlocking(false);
                    // recording to the selector (reading)
                    client.register(selector, SelectionKey.OP_READ);
                    continue;
                }

                // if isReadable = true
                // then the server is ready to read
                if (key.isReadable()) {

                    SocketChannel client = (SocketChannel) key.channel();

                    // Read byte coming from the client
                    int BUFFER_SIZE = 1024;
                    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
                    try {
                        client.read(buffer);
                    } catch (Exception e) {
                        // client is no longer active
                        e.printStackTrace();
                    }

                    // Show bytes on the console
                    buffer.flip();
                    Charset charset = Charset.forName("ISO-8859-1");
                    CharsetDecoder decoder = charset.newDecoder();
                    CharBuffer charBuffer = decoder.decode(buffer);
                    System.out.println("[" + charBuffer.toString() + "]");
                }
            }
        }
    }
}

And here’s my client:

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Client {
    public static void main(String args[]) throws Exception {
        // Create client SocketChannel
        SocketChannel client = SocketChannel.open();

        // nonblocking I/O
        client.configureBlocking(false);

        // Connection to host port 8000
        client.connect(new java.net.InetSocketAddress("127.0.0.1", 8000));

        // Create selector
        Selector selector = Selector.open();

        // Record to selector (OP_CONNECT type)
        SelectionKey clientKey = client.register(selector,
                SelectionKey.OP_CONNECT);

        int counter = 0;
        boolean chk = true;

        // Waiting for the connection
        while (selector.select(500) > 0 && chk) {
            // Get keys
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> i = keys.iterator();

            // For each key...
            while (i.hasNext() && chk) {
                SelectionKey key = (SelectionKey) i.next();

                // Remove the current key
                i.remove();

                // Get the socket channel held by the key
                SocketChannel channel = (SocketChannel) key.channel();

                // Attempt a connection
                if (key.isConnectable()) {

                    // Connection OK
                    System.out.println("Server Found");

                    // Close pendent connections
                    if (channel.isConnectionPending())
                        channel.finishConnect();

                    // Write continuously on the buffer
                    ByteBuffer buffer = null;
                    for (;chk;counter++) {
                        Thread.sleep(1000);
                        buffer = ByteBuffer.wrap(new String(" Client ").getBytes());
                        channel.write(buffer);
                        buffer.clear();

                        if (counter == 2)
                        {
                             chk = false;
                             client.close();
                        }
                    }

                }
            }
        }
    }
}

Anyone can explain what is wrong with my code?
Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T12:19:46+00:00Added an answer on May 31, 2026 at 12:19 pm

    You are probably getting an endless stream of EOS-s from the accepted socket channel. You are ignoring the result of read(). You must at least check it for -1 and if so close the channel.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I am doing a simple coin flipping experiment for class that involves flipping a
I want use html5's new tag to play a wav file (currently only supported
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.