javamultithreadingnioecho-server

Java NIO server in blocking mode not working


I am trying to implement a simple nio server which accepts connection on the 8070 and instantiates a new thread for each of the clients. It basically echoes back the input text read to the client by changing its case.I am able to connect to the server but my expected functionality of the server echoing back is not working. Below is the source code for it. So can someone help me troubleshoot the problems with it?

public class NewIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress("localhost", 8070));
        ExecutorService pool = Executors.newFixedThreadPool(1000);
        while(true) {
            SocketChannel s = ssc.accept();
            pool.submit(new Util(s));
        }
    }
}

public class Util implements Runnable {

    SocketChannel sc;

    public Util(SocketChannel sc) {
        this.sc = sc;
    }

    @Override
    public void run() {
        try {
            process();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void process() throws IOException {
        System.out.println("Connection from:" + this.sc);            
        ByteBuffer buf = ByteBuffer.allocateDirect(1024);
        while(sc.read(buf) != -1) {
            buf.flip();
            for(int i=0; i<buf.limit(); i++) {
                buf.put(i, (byte)transmogrify((int)buf.get(i)));
            }
        }
        sc.write(buf);
        buf.clear();
    }

    public static int transmogrify(int data) {
        if(Character.isLetter(data)) {
            return data ^ ' ';
        }
        return data;
    }
}

PS: I have tried implementing the same functionality with blocking io using serversocket and socket which works fine.


Solution

  • I suggest you step through the code in your debugger. The while loop look completely wrong. I would think you should be writing while in the loop, and you want to clear after writing. Try moving the two lines after the loop, to inside the loop.