SSISO Community

시소당

Java NIO (Non-blocking I/O) with Server-Client Example

Java NIO client server example with Selector and Channels

Java NIO is my favorite topic. I have been working with NIO since last 2 years and would like to share simple Server-Client code for my readers who are free to use this code in their production environment.

Starting JDK 1.4, NIO was created to allow all Java programmers to implement very high-speed input/output without having to deal with custom native code. NIO uses java.nio.buffer library compare to simple I/O which drains and fills back buffer internally any operating system.

In this tutorial we will go over java.nio.channels and java.nio.channels.Selector libraries.

  • channels represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations.
  • selector may be created by invoking the open method of this class, which will use the system’s default selector provider to create a new selector.

java.nio package explanation with API details

If you have below questions then you are at right place:

  • How to get started with Java NIO
  • What is Java NIO and Java NIO tutorials
  • Asynchronous Java NIO
  • What is the exact use of java nio package
  • Java NIO Tutorial
  • How to implement High-Performance I/O with Java NIO

Let’s get started:

Step-1

  • Create CrunchifyNIOServer.java which opens connection on port 1111
  • use isAcceptable() to check if channel is ready to accept a new socket connection
    • If yes – connect it
  • use isReadable() to check if channel is ready for reading
    • if yes – read from buffer and print on Eclipse console
  • Once you get last company name “crunchify”
    • close connection

Step-2

  • Create CrunchifyNIOClient.java which tries to connect to server on port 1111
  • Create ArrayList with 5 company names
  • Iterate through ArrayList and send each companyName to server
  • Close connection after task finish

Take a look at this Java Code:

Server Code – CrunchifyNIOServer.java

Client Code – CrunchifyNIOClient.java

Result at Server Side:

Result at Client Side:

Few FAQs:

  1. From the client, how do I maintain a persistent connection?
    • You could use socket.setKeepAlive(true); to have connections alive from client side.
  2. How do I read a response to the message I send to the server. The server keeps generating messages every 10 sec. I just need to read response to my request. From what I understand, TCP “streams” data instead of end of record, etc.
    • For client server communication, a protocol needs to be well defined. readLine() call will be blocked until all data will be returned, so don’t use it. Try reading bytes from the stream until -1 is returned.

Let me know if that works.

398 view

4.0 stars