devxlogo

Developing a NIO-Based Client

Developing a NIO-Based Client

This tip shows you how to develop a New I/O-based client. As you probably know, NIO offers many advantages such as speed and the ability to maintain a large number of concurrent connections. Here’s the code:

import java.io.*;import java.nio.*;import java.net.*;import java.util.*;import java.nio.channels.*;import java.nio.charset.*;public class ClientNIO{  public static void main(String args[])  {  InetSocketAddress ISA=null;  SocketChannel clientNIO=null;  Selector selector=null;  SelectionKey key=null;    int port=5000;    try{     clientNIO=SocketChannel.open();     clientNIO.configureBlocking(false);          }catch(IOException e)        {System.out.println(e.getMessage());} try{    InetAddress addr=InetAddress.getByName("localhost");    ISA=new InetSocketAddress(addr,port);               }catch(UnknownHostException e)      {System.out.println(e.getMessage());}      try{    clientNIO.connect(ISA);     }catch(IOException e)      {System.out.println(getMessage());}      try{     selector = Selector.open();      }catch(IOException e)          {System.out.println(e.getMessage());}       try{          SelectionKey clientKey=clientNIO.register(selector,SelectionKey.OP_CONNECT);      }catch(Exception e)                {System.out.println(e.getMessage());}             try{            while(selector.select(1000)>0)             {                                       Set keys=selector.selectedKeys();             Iterator iter=keys.iterator();             while(iter.hasNext())                  {                  key=(SelectionKey)iter.next();                  iter.remove();                  SocketChannel channel=(SocketChannel)key.channel();                  if((key.isValid())&&(key.isConnectable()))                      {                      if(channel.isConnectionPending())channel.finishConnect();                      ByteBuffer serverBuf = null;                                            System.out.println("Connected...");                      while(true)                           {                           serverBuf = ByteBuffer.wrap(new String("Answer me dear server ...").getBytes());                           channel.write(serverBuf);                                                                               serverBuf.clear();                                                   ByteBuffer clientBuf = ByteBuffer.allocateDirect(1024);                            clientBuf.clear();                            channel.read(clientBuf);                                                                                                                       clientBuf.flip();                             Charset charset=Charset.forName("ISO-8859-1");                            CharsetDecoder decoder = charset.newDecoder();                              CharBuffer charBuffer = decoder.decode(clientBuf);                            System.out.println(charBuffer.toString());                            clientBuf.clear();                                             }                           }                   }                }     }catch(IOException e)        {System.out.println(e.getMessage());               try{                  key.channel().close();key.cancel();                  }catch(Exception ex)                     {System.out.println(e.getMessage());}}  }
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist