dcsimg
Login | Register   
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 17, 2009

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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

  }
Leonard Anghel
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date