Saturday, April 28, 2012

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());}}
             }                               
      }                                      
    }                                          
  }                                                               
}

No comments:

Post a Comment