devxlogo

Developing a NIO Server

Developing a NIO Server

As you probably know, NIO offers many advantages?like speed and a large number of concurrent connections:

import java.io.*;import java.net.*;import java.nio.*;import java.util.*;import java.nio.channels.*;import java.nio.charset.*;public class ServerNIO{  public static void main(String[] args){  ServerSocketChannel serverNIO=null;  InetSocketAddress ISA=null;  Selector selector=null;  ByteBuffer clientBuf=null;  int port=5000;try{   serverNIO=ServerSocketChannel.open();   serverNIO.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{   ServerSocket SS=serverNIO.socket();   SS.bind(ISA);   System.out.println("- Ready -");   }catch(IOException e)      {System.out.println(e.getMessage());}try{      selector=Selector.open();   serverNIO.register(selector,SelectionKey.OP_ACCEPT);   }catch(IOException e)      {System.out.println(e.getMessage());}     while(true)          {try{              selector.select();              }catch(IOException e)                 {System.out.println(e.getMessage());}                      Set keys=selector.selectedKeys();       Iterator iter=keys.iterator();       while(iter.hasNext())            {            SelectionKey key=(SelectionKey)iter.next();            iter.remove();                        if((key.isValid())&&(key.isAcceptable()))             {                   try{                  ServerSocketChannel SSC=(ServerSocketChannel)key.channel();                                                                          SocketChannel clientNIO=SSC.accept();                             clientNIO.configureBlocking(false);          SelectionKey SK=clientNIO.register(            selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE);                                                                                                                }catch(IOException e)                         {System.out.println(e.getMessage());}                                                         }                        if((key.isValid())&&(key.isReadable()))             {             try{                                SocketChannel clientNIO=(SocketChannel)key.channel();                            clientBuf=ByteBuffer.allocateDirect(1024);                             clientNIO.read(clientBuf);                }catch(IOException e)                  {System.out.println(e.getMessage());                        try{                           key.channel().close();key.cancel();                           }catch(IOException ex)                              {System.out.println(e.getMessage());}}                                                                           clientBuf.flip();                 Charset charset=Charset.forName("ISO-8859-1");                 CharsetDecoder decoder = charset.newDecoder();                 try{                    CharBuffer charBuffer = decoder.decode(clientBuf);                    System.out.println(charBuffer.toString());                    clientBuf.clear();                                                              }catch(IOException e)                       {System.out.println(e.getMessage());}                                        }                       if((key.isValid())&&(key.isWritable()))               {               SocketChannel clientNIO=(SocketChannel)key.channel();               ByteBuffer serverBuf=ByteBuffer.allocateDirect(1024);                try{                  String s="Message from server ...";                  serverBuf.put(s.getBytes());                   serverBuf.flip();                  clientNIO.write(serverBuf);                                                                              }catch(IOException e)                    {System.out.println(e.getMessage());                    try{                       key.channel().close();key.cancel();                       }catch(IOException ex)                          {System.out.println(ex.getMessage());}}             }                                     }                                          }                                            }                                                               }
See also  5 Strategies for Supercharging Your CRM
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