Java NIO client

I need to make the server is able to hold about 500 connections and operates on a single thread. The server itself should make all the connections. Where can I find examples of finished implementations?

I have an example, but it does not work
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.*;
public class NioClient implements Runnable {
     // The host:port combination to connect to
     private InetAddress hostAddress;
     private String host;
     private int port;
     // The selector we'll be monitoring
     private Selector selector;
     // The buffer into which we'll read data when it's available
     private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
     // A list of PendingChange instances
     private List pendingChanges = new LinkedList();
     // Maps a SocketChannel to a list of ByteBuffer instances
     private Map pendingData = new HashMap();
     // Maps a SocketChannel to a RspHandler
     private Map rspHandlers = Collections.synchronizedMap(new HashMap());
     public NioClient() {
          try {this.selector = this.initSelector();} catch(IOException e){}
     public void connect(String host, int port, RspHandler handler) throws IOException {
          this.hostAddress = hostAddress;
          this.host = host;
          this.port = port;
          this.send("$Hello |".getBytes(), handler);
     public void send(byte[] data, RspHandler handler) throws IOException {
          // Start a new connection
          SocketChannel socket = this.initiateConnection();
          // Register the response handler
          this.rspHandlers.put(socket, handler);
          // And queue the data we want written
          synchronized (this.pendingData) {
               List queue = (List) this.pendingData.get(socket);
               if (queue == null) {
                    queue = new ArrayList();
                    this.pendingData.put(socket, queue);
               queue.add(ByteBuffer.wrap(data));
          // Finally, wake up our selecting thread so it can make the required changes
          this.selector.wakeup();
          handler.waitForResponse();
     public void run() {
          while (true) {
               try {
                    // Process any pending changes
                    synchronized (this.pendingChanges) {
                         Iterator changes = this.pendingChanges.iterator();
                         while (changes.hasNext()) {
                              ChangeRequest change = (ChangeRequest) changes.next();
                              switch (change.type) {
                              case ChangeRequest.CHANGEOPS:
                                   SelectionKey key = change.socket.keyFor(this.selector);
                                   key.interestOps(change.ops);
                                   break;
                              case ChangeRequest.REGISTER:
                                   change.socket.register(this.selector, change.ops);
                                   break;
                         this.pendingChanges.clear();
                    // Wait for an event one of the registered channels
                    this.selector.select();
                    // Iterate over the set of keys for which events are available
                    Iterator selectedKeys = this.selector.selectedKeys().iterator();
                    while (selectedKeys.hasNext()) {
                         SelectionKey key = (SelectionKey) selectedKeys.next();
                         selectedKeys.remove();
                         if (!key.isValid()) {
                              continue;
                         // Check what event is available and deal with it
                         if (key.isConnectable()) {
                              this.finishConnection(key);
                         } else if (key.isReadable()) {
                              this.read(key);
                         } else if (key.isWritable()) {
                              this.write(key);
               } catch (Exception e) {
                    e.printStackTrace();
     private void read(SelectionKey key) throws IOException {
          SocketChannel socketChannel = (SocketChannel) key.channel();
          // Clear out our read buffer so it's ready for new data
          this.readBuffer.clear();
          // Attempt to read off the channel
          int numRead;
          try {
               numRead = socketChannel.read(this.readBuffer);
          } catch (IOException e) {
               // The remote forcibly closed the connection, cancel
               // the selection key and close the channel.
               key.cancel();
               socketChannel.close();
               return;
          System.out.println("READ");
          if (numRead == -1) {
               // Remote entity shut the socket down cleanly. Do the
               // same from our end and cancel the channel.
               key.channel().close();
               key.cancel();
               return;
          // Handle the response
          this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
     private void handleResponse(SocketChannel socketChannel, byte[] data, int numRead) throws IOException {
          // Make a correctly sized copy of the data before handing it
          // to the client
          byte[] rspData = new byte[numRead];
          System.arraycopy(data, 0, rspData, 0, numRead);
          // Look up the handler for this channel
          RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
          // And pass the response to it
          if (handler.handleResponse(rspData)) {
               // The handler has seen enough, close the connection
               socketChannel.close();
               socketChannel.keyFor(this.selector).cancel();
     private void write(SelectionKey key) throws IOException {
          SocketChannel socketChannel = (SocketChannel) key.channel();
          synchronized (this.pendingData) {
               List queue = (List) this.pendingData.get(socketChannel);
               // Write until there's not more data ...
               while (!queue.isEmpty()) {
                    ByteBuffer buf = (ByteBuffer) queue.get(0);
                    socketChannel.write(buf);
                    if (buf.remaining() > 0) {
                         // ... or the socket's buffer fills up
                         break;
                    queue.remove(0);
               if (queue.isEmpty()) {
                    // We wrote away all data, so we're no longer interested
                    // in writing on this socket. Switch back to waiting for
                    // data.
                    key.interestOps(SelectionKey.OP_READ);
     private void finishConnection(SelectionKey key) throws IOException {
          SocketChannel socketChannel = (SocketChannel) key.channel();
          // Finish the connection. If the connection operation failed
          // this will raise an IOException.
          try {
               socketChannel.finishConnect();
          } catch (IOException e) {
               // Cancel the channel's registration with our selector
               System.out.println(e);
               key.cancel();
               return;
          // Register an interest in writing on this channel
          key.interestOps(SelectionKey.OP_WRITE);
     private SocketChannel initiateConnection() throws IOException {
          // Create a non-blocking socket channel
          SocketChannel socketChannel = SocketChannel.open();
          socketChannel.configureBlocking(false);
          // Kick off connection establishment
          socketChannel.connect(new InetSocketAddress(this.host, this.port));
          // Queue a channel registration since the caller is not the
          // selecting thread. As part of the registration we'll register
          // an interest in connection events. These are raised when a channel
          // is ready to complete connection establishment.
          synchronized(this.pendingChanges) {
               this.pendingChanges.add(new ChangeRequest(socketChannel, ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
          return socketChannel;
     private Selector initSelector() throws IOException {
          // Create a new selector
          return SelectorProvider.provider().openSelector();
public class RspHandler {
     private byte[] rsp = null;
     public synchronized boolean handleResponse(byte[] rsp) {
          this.rsp = rsp;
          this.notify();
          return true;
     public synchronized void waitForResponse() {
          while(this.rsp == null) {
               try {
                    this.wait();
               } catch (InterruptedException e) {
          System.out.println(new String(this.rsp));
}          NioClient NioClient = new NioClient();
          Thread t = new Thread(NioClient);
          t.setDaemon(true);
          t.start();
          RspHandler handler = new RspHandler();          
          NioClient.connect("69.28.156.250", 27040, handler);
          NioClient.connect("72.165.61.188", 27040, handler);
          NioClient.connect("208.111.133.84", 27011, handler);
          NioClient.connect("72.165.61.136", 27012, handler);
Edited by: 915967 on 01.08.2012 7:07

Similar Messages

  • Java.nio select() method return 0 in my client application

    Hello,
    I'm developing a simple chat application who echo messages
    But my client application loop because the select() method return 0
    This is my code
    // SERVER
    package test;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class Server {
         private int port = 5001;
         public void work() {               
              try {
                   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                   serverSocketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(port);               
                   serverSocketChannel.socket().bind(isa);
                   Selector selector = Selector.open();
                   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Listing on "+port);
                   while(selector.select()>0) {
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isAcceptable()) {
                                  ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();                              
                                  SocketChannel channel = keyChannel.accept();
                                  channel.configureBlocking(false);                              
                                  channel.register(selector, SelectionKey.OP_READ );
                             } else if (key.isReadable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel );
                                  Help.write(m.toUpperCase(), keyChannel );
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         public static void main(String[] args) {
              Server s = new Server();
              s.work();
    // CLIENT
    package test;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {               
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);               
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
                   while(true) {
                        selector.select();
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  if (keyChannel.isConnectionPending()) {
                                       System.out.println("Connected "+keyChannel.finishConnect());                                                                           
                             } else if (key.isReadable()) {                                                                                                                                                           
                                  SocketChannel keyChannel = (SocketChannel) key.channel();                                             
                                  String m = Help.read(keyChannel);
                                  display(m);                                                                                                                                                                                                                   
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {               
                   public void run() {                                                                                
                        try {                         
                             Help.write(m, socketChannel);
                        } catch (IOException e) {               
                             e.printStackTrace();
              t.start();                    
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);     
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();
    // HELPER CLASS
    package test;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    public class Help {
         private static Charset charset = Charset.forName("us-ascii");
         private static CharsetEncoder enc = charset.newEncoder();
         private static CharsetDecoder dec = charset.newDecoder();
         private static void log(String m) {
              System.out.println(m);
         public static String read(SocketChannel channel) throws IOException {
              log("*** start READ");                              
              int n;
              ByteBuffer buffer = ByteBuffer.allocate(1024);
              while((n = channel.read(buffer)) > 0) {
                   System.out.println("     adding "+n+" bytes");
              log("  BUFFER REMPLI : "+buffer);
              buffer.flip();               
              CharBuffer cb = dec.decode(buffer);          
              log("  CHARBUFFER : "+cb);
              String m = cb.toString();
              log("  MESSAGE : "+m);          
              log("*** end READ");
              //buffer.clear();
              return m;                    
         public static void write(String m, SocketChannel channel) throws IOException {          
              log("xxx start WRITE");          
              CharBuffer cb = CharBuffer.wrap(m);
              log("  CHARBUFFER : "+cb);          
              ByteBuffer  buffer = enc.encode(cb);
              log("  BUFFER ALLOUE REMPLI : "+buffer);
              int n;
              while(buffer.hasRemaining()) {
                   n = channel.write(buffer);                         
              System.out.println("  REMAINING : "+buffer.hasRemaining());
              log("xxx end WRITE");

    Here's the fix for that old problem. Change the work method to do the following
    - don't register interest in things that can't happen
    - when you connect register based on whether the connection is complete or pending.
    - add the OP_READ interest once the connection is complete.
    This doesn't fix all the other problems this code will have,
    eg.
    - what happens if a write is incomplete?
    - why does my code loop if I add OP_WRITE interest?
    - why does my interestOps or register method block?
    For code that answers all those questions see my obese post Taming the NIO Circus
    Here's the fixed up Client code
    // CLIENT
    package test
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   int interest = 0;
                   if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
                   else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
                   socketChannel.register(selector, interest);
                   while(true)
                        int nn = selector.select();
                        System.out.println("nn="+nn);
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();)
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  System.out.println("Connected "+keyChannel.finishConnect());
                                  key.interestOps(SelectionKey.OP_READ);
                             if (key.isReadable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel);
                                  display(m);
              } catch (IOException e) {
                   e.printStackTrace();
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {
                   public void run() {
                        try {
                             Help.write(m, socketChannel);
                        } catch (IOException e) {
                             e.printStackTrace();
              t.start();
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();

  • Problematic frame: # J java.nio.MappedByteBuffer.load()

    Helo all...
    I'm getting an error when generating a PDF using BIRT Framework in Eclipse. Nothing fancy, just compiling a simple report to pdf.
    The problem is, the JVM crashes with the following error:
    # A fatal error has been detected by the Java Runtime Environment:
    # EXCEPTION_IN_PAGE_ERROR (0xc0000006) at pc=0x0190f0be, pid=5848, tid=2392
    # JRE version: 7.0_09-b05
    # Java VM: Java HotSpot(TM) Client VM (23.5-b02 mixed mode, sharing windows-x86 )
    **# Problematic frame:
    # J java.nio.MappedByteBuffer.load()Ljava/nio/MappedByteBuffer;**
    # Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
    # An error report file with more information is saved as:
    # C:\Users\luis\Desktop\teste\birt\hs_err_pid5848.log
    # If you would like to submit a bug report, please visit:
    # http://bugreport.sun.com/bugreport/crash.jsp
    I already tried:
    1. Run the program in another computers - it worked
    2. Reinstall Java on the computer - It did nothing
    3. I check the integrity of the disk C: - Nothing
    I already spent two days trying to fix this and I don't have any progress. I can't find a solution on the web either.
    Thanks in advance

    Thanks for the help.
    But it can not be related to BIRT because it works in every other computer that I tried so far. There is only one computer that not works properly.
    If it were BIRT's fault, it wouldn't work in any computer.
    Thanks again

  • Java NIO, ByteBuffers and Linksys router

    I have a client server app/game that uses NIO for communication sending ByteBuffers. On a LAN with 5-8 users it runs great. On the internet, through a Linksys router, with one user, it has a blip. I get all my data transmissions except for one buffer. Whenever I chat the buffer contains a size, an int typeID and the encoded string for chat. This particular buffer never makes it to the client on the outside of the router. I have a port forwarded and regular tcp/ip java io sockets stuff works fine. As does al lof the other NIO buffer traffic for locational data, login in and out, etc... ANy thoughts??

    But not sure what would be the performance of those clients?? when compared to Java NIO performance....Telnet isn't a high-performance protocol anyway. Don't worry about it. Use existing code. Get it working. Measure. If you have a performance issue, then worry, while at least you have something you can deploy. It won't be a problem. The router is there to route, not to talk high-speed telnet.

  • Java NIO's puzzle

    hi,all
    In traditonal thread-pool based programming way,the Server can process multi-clients by thread(time-sharing),all clients's time is equal.
    In Java NIO programming way,the [select] will process multi-clients without thread pool.So,the the second client must be processed after the first client be complished.if the first client is cost much time,other cients must be long time waiting?
    plz help me - thanks for your time
    Tony.
    Hangzhou,china

    As an NIO server in non-blocking mode obviously never blocks (or rather it only blocks in select(), when nothing is happening), it can implement any kind of scheduling it likes between the various SocketChannels it has accepted as connected clients. It isn't obliged in any way to completely finish with one client before starting on the next, and it generally can't do so because data from any particular client doesn't necessarily arrive in a single chunk.

  • Java.nio read/write question

    Hello,
    I just started to learn the java.nio package so I decided to make a simple Echo server. I made a client which reads a line from the keyboard, sends it to the server and the server returns it. It all works except one little detail. Here's little code from the server:
                                 int n = client.read(buffer);
                                 if ( n > 0)
                                     buffer.flip();
                                     client.write(buffer);
                                     Charset charset = Charset.forName("ISO-8859-1");
                                     CharsetDecoder decoder = charset.newDecoder();
                                     charBuffer = decoder.decode(buffer);
                                     System.out.println(charBuffer.toString());
                                     buffer.clear();
                                  }So that works, I send the data and then I receive it back. But only for the client. I also wanted the server to print the line which is the reason for the charset and the decoder. The above code however prints only a blank line. Thus I tried this:
                                 int n = client.read(buffer);
                                 if ( n > 0)
                                     buffer.flip();
                                     Charset charset = Charset.forName("ISO-8859-1");
                                     CharsetDecoder decoder = charset.newDecoder();
                                     charBuffer = decoder.decode(buffer);
                                     System.out.println(charBuffer.toString());
                                     client.write(buffer);
                                     buffer.clear();
                                  }Or in other words I just moved the write() part downwards. So far so good, now the server was actually printing the lines that the client was sending but nothing was sent back to the client.
    The question is how to make both, the send back line and the print line on the server side to work as intended. Also a little explanation why the events described above are happening is going to be more than welcome :)
    Thanks in advance!

    Strike notice
    A number of the regular posters here are striking in protest at the poor
    management of these forums. Although it is our unpaid efforts which make the
    forums function, the Sun employees responsible for them seem to regard us as
    contemptible. We hope that this strike will enable them to see the value
    which we provide to Sun. Apologies to unsuspecting innocents caught up in
    the cross-fire.

  • Help "ascending" to Java NIO

    Hello there.
    I've been using Java for quite some time, but the few really networked client/server applications I have used, have used java.io and java.net. Now, even I have heard the rumours about Java NIO, and I am curious. I have tried reading up and down the API on java.nio.* , but I must say I am still kind of confused.
    Basically, I am looking for some example code, or a thorough explanation of how all the classes and components come together to form efficient asynchronous non-blocking I/O.
    What I picture is a server over TCP/IP meant to handle 100+ clients, written with an emphasis on performance. Think MMORPG, I guess (no no, I am not ambitious enough to want to write one, but I can imagine that gives a good analogy of how I would have the communication set up). The server needs to quickly figure out which clients need to be handled at any given time, with as little overhead or reduntant iteration as possible.
    Ok, I am asking alot perhaps.. I just wonder if anyone could offer links to example source-code, write something to show me, or basically just try to explain to me how this all works.
    I would be very very grateful if anyone stepped up to the plate.
    Thanks,
    -Terje

    Take a look at my thread Taming the NIO Circus. It starts with simple examples of a single thread echo server and a swing client.

  • DPS 11.1.1.5.0 java.nio.channels.ClosedChannelException

    Hi,
    I've upgraded today to 11.1.1.5.0 all my DS and DPS from 11.1.1.3.0 on Redhat 5.6 x64, Java(TM) SE Runtime Environment (build 1.6.0_27-b07)
    I get this on my proxy after a while:
    [29/Aug/2011:17:08:08 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:124 failed. java.nio.channels.ClosedChannelException
    [29/Aug/2011:17:08:08 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:124 failed. java.nio.channels.ClosedChannelException
    On the LDAP server I get
    [29/Aug/2011:17:22:49 +0300] conn=91 op=766568 msgId=1 - SRCH base="" scope=0 filter="(objectClass=*)" attrs="1.1"
    [29/Aug/2011:17:22:49 +0300] conn=91 op=766568 msgId=1 - RESULT err=0 tag=101 nentries=1 etime=0
    which is DOSing my log file.
    If I restart the proxy server the problem is gone for a while but it gets back after an hour or so thus making my whole LDAP infrastructure unusable.
    regards,
    Giannis

    I disabled proactive monitor for failed server and the problem didn't occur for 15 hours. Then I got the following.
    Just for the record, ldap.example.com is running on the same machine as DPS.
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:05 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Worker Thread 25. Abandon current operation.
    [30/Aug/2011:09:08:05 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:06 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Worker Thread 36. Abandon current operation.
    [30/Aug/2011:09:08:07 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Connection Handler 0 for Listener Thread 0.0.0.0:1636
    Exception thrown from thread Connection Handler 0 for Listener Thread 0.0.0.0:1636 java.lang.OutOfMemoryError: GC overhead limit exceeded
    [30/Aug/2011:09:08:07 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Connection Handler 0 for Listener Thread 0.0.0.0:1636. Disconnecting all client connections.
    [30/Aug/2011:09:08:08 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Connection Handler 1 for Listener Thread 0.0.0.0:1636
    Exception thrown from thread Connection Handler 1 for Listener Thread 0.0.0.0:1636 java.lang.OutOfMemoryError: GC overhead limit exceeded
    [30/Aug/2011:09:08:08 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Connection Handler 1 for Listener Thread 0.0.0.0:1636. Disconnecting all client connections.
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for ds.example.com:636/
    Exception thrown from thread Proactive Monitor for ds.example.com:636/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for dscc.example.com:3998/
    Exception thrown from thread Proactive Monitor for dscc.example.com:3998/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for dscc.example.com:3998/
    Exception thrown from thread Proactive Monitor for dscc.example.com:3998/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Proactive Monitor for ds.example.com:636/. No more monitoring running on ds.example.com:636/
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Proactive Monitor for dscc.example.com:3998/. No more monitoring running on dscc.example.com:3998/
    [30/Aug/2011:09:08:17 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for ldap.example.com:2389/
    Exception thrown from thread Proactive Monitor for ldap.example.com:2389/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:17 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for ldapexample.com:3389/
    Exception thrown from thread Proactive Monitor for ldap.example.com:3389/ java.lang.OutOfMemoryError: GC overhead limit exceeded
    I changed all servers to reactive monitor and will see what's going on.
    Giannis

  • Socket disconnection event not being reveived java.nio

    Hi All
    My question is as below
    i am using java.nio package + win 2K + jdk1.4.1_02
    I have a Server accepting socket connection and is configured
    in Nonblocking mode.
    -The server receives (selector) events (accept event)
    when a client requests for a connection .
    -The server is getting read and write events when
    client wants to read and write
    -The server gets a read event when the client disconnects
    My only problem is that the Server is not getting any events
    when the client disconnect due to network break down
    for EX when the network connection breaks the client disconnects
    but the server selector is not getting any events
    I am storing the client Socket objects in a Hash Table and
    if i execute the .isConnected() method it returns true
    even though the the client is down
    The only work around is to try to read and write on the socket
    i get an IO exception and am able to make out that the
    client is disconnected
    But this is not desirable for my client
    as client modification to give any kind of echo is not possible and
    a read /write event will cause problem.
    Can any one tell how to detect client side disconnection
    with out Read and Write on the client socket
    I get an socket Exception when the socket is in Blocking IO and is blocked on read/ write but I am facing this problem in NonBlockingIO
    Regards
    Avinash

    int ct = read.selectNow();
    if (ct > 0)
    Set readyKeys = read.selectedKeys();
    Iterator i = readyKeys.iterator();
    while (i.hasNext())
    SelectionKey key = (SelectionKey) i.next();
    i.remove();
    if (key.isReadable())
    SelectableChannel nextReady = (SelectableChannel) key.channel();
    SocketChannel sc = (SocketChannel) key.channel();
    int rd = sc.read(buffer);
    // Link is dead
    if (rd == -1)
    key.cancel();
    key.attach(null);
    nextReady.close();
    continue;
    // Process your data
    catch (Exception e)
    e.printStackTrace();

  • Java server/client archetecture

    how would I go about setting up a connection with a client and maintaining it by sending info back and fourth

    1. java.net.ServerSocket and java.net.Socket
    2. java.nio.channels.ServerSocketChannel and java.nio.channels.SocketChannel
    3. Mixture of the above.
    4. RMI
    5. RMI/IIOP
    6. IDL
    7. Web services
    and there are more ...

  • Java NIO and sockets in 1.4.1FCS

    Hi,
    I have built a client server system using the new 1.4 java.nio packages. In 1.4 everything worked fine, yet in 1.4.1 FCS it definitely does not. The process is as follows.
    Everything work in non-blocking mode:
    - Server receives connection and accepts it, the new SocketChannel is put in non-blocking mode and registered with the same selector as the server.
    - New SocketChannel waits for data from the client so it waits for OP_READ from the selector. All it gets is OP_WRITE, OP_CONNECT. With 1.4 it received OP_READ, OP_WRITE.
    I tried adding a call to finishConnect, but that didn't help.
    Anyone have any thoughts about this?
    Thanks,
    Mike.

    The code in the bug report is incorrect. The key will of course always be writable if you do not write anything to the socket! And since it is writable the readable part of the code will never be executed (its in an else-statement). When you are not interested in the OP_WRITE, change the ops on the selection key.

  • The java.nio circus - what a headache

    Hi All
    I've been working now with the java.nio classes for a bit and trying to get a non-blocking client HTTP socket going. The requirement: no 3rd-party code and must either read fully from the socket OR timeout quickly (say 10sec).
    Unfortunately, I haven't been able to find ANY nio code that actually does this. There was one example by a John Z. that came really close, but it hung after a full reading of an HTTP stream because it could not determine if it was done reading or not!
    Anyway, here's my full code. It's very hacky and piecemeal, but i'm just looking for a prototype.
    Here's the main processing loop, cobbled together from a mix of examples on the web, plus my own little flourishes... :)
    public static void createSelector(URL url) throws IOException
    // Create a selector and register two socket channels
    Selector selector = null;
    // Create the selector
    selector = Selector.open();
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);
    int port = url.getPort();
    if (port == -1) { port = 80; }
    sChannel.connect(new InetSocketAddress(url.getHost(), port));
    // Before the socket is usable, the connection must be completed
    // by calling finishConnect(), which is non-blocking
    int iTime = 0;
    while (!sChannel.finishConnect())
         if (iTime > 10)
              System.out.println("Timeout!");
              throw new IOException("Connection timed out!");
         iTime++;
    System.out.println("Waiting for connection...");
    try { Thread.sleep(1000); } catch (InterruptedException interex) {}
    // Register the channel with selector, listening for all events
    //sChannel.register(selector, sChannel.validOps());
    sChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
    boolean allDone = false;
    while (selector.select(5000) > 0)
    // Get list of selection keys with pending events
    Iterator it = selector.selectedKeys().iterator();
    // Process each key at a time
    while (it.hasNext())
    // Get the selection key
    SelectionKey selKey = (SelectionKey)it.next();
    // Remove it from the list to indicate that it is being processed
    it.remove();
    allDone = processSelectionKey(selKey, url);
    if (allDone) { break; }
    } // while(true)
    if (allDone)
    System.out.println("All done!");
    else
         System.out.println("Timeout!");
    Now, the processSelectionKey method returns a true only if we get a -1 on our read. It looks like this:
    public static boolean processSelectionKey(SelectionKey selKey, URL url) throws IOException
    // Since the ready operations are cumulative,
    // need to check readiness for each operation
    if (selKey.isValid() && selKey.isConnectable())
    // Get channel with connection request
    SocketChannel sChannel = (SocketChannel)selKey.channel();
    //System.out.println("Sending request for "+url.getPath()+" using Connectable stream");
    String request = "GET "+url.getPath()+" \r\n\r\n";
    //System.out.println("Writing request "+request);
    sChannel.write(NonblockSocket.encoder.encode(CharBuffer.wrap(request)));
    //sentRequest = true;
    if (selKey.isValid() && selKey.isReadable())
         System.out.println("Readable key!");
    // Get channel with bytes to read
    SocketChannel sChannel = (SocketChannel)selKey.channel();
    int bytesRead = sChannel.read(buf);
    if (bytesRead == -1)
         return true;
    else
         System.out.println("Read "+bytesRead+" bytes...");
    buf.flip();
    System.out.println(decode(buf));
    buf.clear();
    cbuf.clear();
    OK, now this code does not work. There are a couple of problems with it. First of all, the "GET "+urlpath+" \r\n\r\n" is called a WHOLE BUNCH of times, not the usual once-per-request, as you would expect. But, if I programmatically enforce only one GET, it hangs. Still, it's strange.
    Secondly (and this is the real sticky point), it almost never reads in a full HTTP stream from the server before I get the following UNSETTLING exception during a read from the Channel:
    java.io.IOException: An existing connection was forcibly closed by the remote host
    I usually get either one or two successful reads from a readable channel and then the server disconnects me! NEVER saw this one coming. All in all, has ANYONE been able to use nio for client-side stuff to ANY degree at all? Maybe I'm doing something wrong? Any help would be excellent. BTW I'm running Win2K with JDK1.4.1.
    If I can't get this one to work, maybe I'll check out the new additions to the "old-school" java.net Socket.

    Actually,
    I just wrote a if..then to ignore the null accept.
    Even without using non-blocking connect i got two accepts.
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.nio.charset.*;
    import java.io.*;
    import java.util.*;
    * @author Aashish
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class NonBlockingServerSocket
         public static void main(String[] args)
              try
                        ServerSocketChannel serv = ServerSocketChannel.open();
                        serv.configureBlocking(false);
                        serv.socket().bind(new InetSocketAddress(33333));
                        System.out.println("bind complete");
                        Selector selector = Selector.open();
                        serv.register(selector,SelectionKey.OP_ACCEPT);
                        while(selector.select() > 0)
                             Iterator iter = selector.selectedKeys().iterator();
                             while(iter.hasNext())
                                  SelectionKey key = (SelectionKey)iter.next();
                                  if(key.isAcceptable())
                                       ServerSocketChannel servChan = (ServerSocketChannel)key.channel();
                                       SocketChannel sockChan = servChan.accept();
                                       if(sockChan == null)
                                            System.out.println("Just got a null channel in accept");
                                       else
                                            System.out.println("just accepted a sockChan");
                                            sockChan.configureBlocking(false);
                                           sockChan.register(selector,SelectionKey.OP_READ);
                                           if(sockChan.isConnected())
                                                 System.out.println("Channel is connected");
                                  if(key.isReadable())
                                                        //something here
              catch (Exception ex)
                   ex.printStackTrace();

  • Troubles with timeout using java.nio.channels and non-blocking sockets

    Hello.
    I have a server application that employs java.nio.channels with non-blocking sockets.
    The server waits for connections. The client should connect and be first in sending data.
    Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.
    The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
    My code looks as follows:
    <pre>
    Selector oSel;
    SocketChannel oSockChan;
    Socket oSock;
    SelectionKey oSelKey;
    Iterator<SelectionKey> oItSelKeys;
    int iCurrState, iMask, iCount;
    iCurrState = INT_SERVER_WORKING;
    iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    while ( iCurrState == INT_SERVER_WORKING )
    try
    *// retrieving next action*
    iCount = oSel.select();
    if ( iCount > 0 )
    oItSelKeys = oSel.selectedKeys().iterator();
    while ( oItSelKeys.hasNext() )
    oSelKey = oItSelKeys.next();
    oItSelKeys.remove();
    if ( oSelKey.isValid() )
    switch ( oSelKey.readyOps() & iMask ) {
    case SelectionKey.OP_ACCEPT :
    oSockChan = oSSockChan.accept();
    oSockChan.configureBlocking(false);
    oSock = oSockChan.socket();
    oSock.setKeepAlive(true);
    oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
    break;
    case SelectionKey.OP_READ :
    oSelKey.interestOps(0);
    ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
    this.getReader().add(oSelKey); *// sending key to reading thread*
    break;
    case SelectionKey.OP_WRITE :
    oSelKey.interestOps(0);
    ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
    this.getWriter().add(oSelKey); *// sending key to writing thread*
    break;
    case SelectionKey.OP_CONNECT :
    default :
    *// nothing to do*
    catch ( IOException oExcept )
    *// do some actions*
    </pre>
    Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
    But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!
    Please help with idea how can I terminate such connections!

    How can I process the keys that weren't selected at the bottom of the loop? Should I use the method keys() ?Yes. Form a new set from keys() and removeAll(selectedKeys()). Do that before you process selectedKeys().
    And the second moment: as I understood a single key may contain several operations simultaneously? Thus I should use several if's (but not if/else 'cause it's the equivalent of switch ... case ).If there is anything unclear about 'your switch statement is invalid. You need an if/else chain' I fail to see what it is. Try reading it again. And if several ifs were really the equivalent of "switch ... case", there wouldn't be a problem in the first place. They're not, and there is.

  • Does JMQ 3.5 SP1 Enterprise Edition use Java NIO anywhere?

    Hi,
    I was wondering, does anyone know whether JMQ 3.5 SP1 Enterprise Edition uses Java NIO anywhere?
    Cheers, Andrew

    Yes ...
    java.nio is not used on the client (because it needs to support older
    jdk's), however we do use nio on the broker.
    java.nio is used:
    - in the "channels" support in the shared thread pool to allow
    non-blocking reads
    - we use the various Buffer classes for reading,writing and
    persisting some of our data

  • Announcement: Java NIO Framework

    Hi all,
    After reading Ron Hitchen's book "Java NIO" and watching his presentation "How to Build a Scalable Multiplexed Server With NIO" at the 2006 JavaOne Conference, I implemented a framework based on his ideas.
    Here is the website: http://nioframework.sourceforge.net/
    I would be very glad if you could take a look and tell me what you think about it.
    Regards and thanks for your input!
    Ronny Standtke
    PS: I will add dukes to this topic and spend it for contributors (found bugs, hints, ...).

    Finally I found the time to write some benchmark programs for the NIO Framework and take a look at the MINA API.
    If you download the latest NIO Framework release you can run the plaintext benchmark as follows:
    Start the benchmark server (this is just the echo server without any session debugging output or logging) with the following command:
    java -cp nio_framework-0.9.3_all.jar ch.unifr.nio.framework.examples.BenchmarkServer 8080
    Then start the benchmark client with the follwing command:
    java -cp nio_framework-0.9.3_all.jar ch.unifr.nio.framework.examples.BenchmarkClient localhost 8080
    On my machine the resulting bandwidth is around 80 MB/s.
    And now to MINA:
    I used the very simple echo server example from the MINA project and just removed the logger from the chain. You may download this package from here (it includes all relevant source code):
    http://nioframework.sourceforge.net/mina_echo_server.jar
    You can start this server with the following command:
    java -jar mina_echo_server.jar
    If I run my BenchmarkClient against the MINA echo server the resulting bandwidth is only around 20 KB/s!? That is about 4000 times slower.
    Is MINA really THAT slow? I seriously doubt that. Are there any stops that I have to pull to get a higher bandwidth with MINA?

Maybe you are looking for

  • Help!  Dreamweaver Opens Automatically with Browser

    Hi everyone, I'm using a trial of CS5.  I don't use Dreamweaver, but something during the trial popped up and asked something about my browser settings.  I thought I just closed the window, but now Dreamweaver opens EVERY TIME I open a new browser wi

  • Where is the default hard drive location for an ipod backup?

    Where is the default location on a Window hard drive for iPod backups? Thanks!

  • InDesign quits when I try to make pdf

    I just got a new MacBook Air with twice the solid state drive of my old one. I installed InDesign CS3 on it and tried to make some pdfs. In certain files, when I use either the Export or Adobe PDF Preset command, after entering the file name and clic

  • Dynamically set tab

    I have a bunch of forms and reports which are identical. However depending on how the user gets to the form the parent may be a different entity. I would like to be able to dynamically set the tab for the form so that the form appears in the tab for

  • Editing Hindi documents

    Dear All, I face a regular issue with copy-paste of hindi text from pdf documents , im' just unable to reproduce the same hindi on using the paste option. Am i missing some particular font , package or additional download from the reader instaallatio