dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java
Expertise: Advanced
Feb 4, 2009

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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());}}
             }                               
      }                                      
    }                                          
  }                                                               
}
Leonard Anghel
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date