Wierdness with NIO socket on Solaris 2.10 part I

i tried the following NioClient and MockServer, and saw some weird behavior.
1. If i run both the client and server on the same machine on Windows, the client connects to the server, queries the instrument and gets the list of instruments back.
2. if i run both client and server on the same Solaris 2.10 box, the NioClient doesn't get anything back from the MockServer, not even an ACCEPT
3. if i run the client and the server on different solaris 2.10 machines, they work fine.
have anyone seen this before? can sometone sheds some lights?
import java.net.*;
import java.io.*;
public class MockServer
     public static int counter = 2;
    public static void main(String[] args) throws IOException {
         int portNumber = Integer.parseInt(args[0]);
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(portNumber);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + portNumber);
            System.exit(1);
         System.out.println ("Listening on socket " + portNumber);
        do {             
             Socket clientSocket = null;
             try {
                 clientSocket = serverSocket.accept();
                 System.out.println ("starting a new client....");
                 MyThread mt = new MyThread (clientSocket);
                 mt.run ();
             } catch (IOException e) {
                 System.err.println("Accept failed.");
                 System.exit(1);
        while (true);
class MyThread
     private final Socket clientSocket;
     MyThread (Socket clientSocket)
          this.clientSocket = clientSocket;
     public void run ()
        new Thread (new Runnable () {
                 public void run ()
                      try
                           boolean instrumentquery = false;
                           PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                           BufferedReader in = new BufferedReader(
                                       new InputStreamReader(
                                       clientSocket.getInputStream()));
                           String inputLine;                          
                           String successoutputLine =
                                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><return><returncode>success</returncode><detail>everything is good</detail></return>";
                           String failoutputLine =
                                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><return><returncode>failure</returncode><detail>something is not good</detail></return>";
                           String instrumentsoutput =
                                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><instruments><instrument><contract>usg-505Y</contract><cusip>12131121</cusip><deactivated>false</deactivated><halted>false</halted></instrument><instrument><contract>usg-305Y</contract><cusip>121312342</cusip><deactivated>false</deactivated><halted>false</halted></instrument></instruments>";
                           while ((inputLine = in.readLine()) != null) {
                                System.out.println ("Receiving the following" + inputLine);
                                if (inputLine.contains("queryInstrument")) instrumentquery = true;
                                if (inputLine.contains("</a>"))
                                     if (instrumentquery)
                                          instrumentquery = false;
                                          System.out.println ("Sending " + instrumentsoutput);
                                          out.println (instrumentsoutput);
                                     else
                                          if ((MockServer.counter % 2) == 0)
                                               System.out.println ("Sending " + successoutputLine);
                                               out.println(successoutputLine);
                                          else
                                               System.out.println ("Sending " + failoutputLine);
                                               out.println(failoutputLine);
                                          MockServer.counter++;
                           out.close();
                           in.close();
                           clientSocket.close();}
                      catch (Exception ex)
             }).start (); }
}please see topic "wierdness with NIO socket on Solaris 2.10 part II" for the NioClient code as the maximum per topic is 5000.

code for NioClient.java
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 {
private InetAddress hostAddress;
private int port;
private Selector selector;
private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
private List pendingChanges = new LinkedList();
private Map pendingData = new HashMap();
private Map rspHandlers = Collections.synchronizedMap(new HashMap());
public NioClient(InetAddress hostAddress, int port) throws IOException {
this.hostAddress = hostAddress;
this.port = port;
this.selector = this.initSelector();
public void send(byte[] data, RspHandler handler) throws IOException {
SocketChannel socket = this.initiateConnection();
this.rspHandlers.put(socket, handler);
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));
this.selector.wakeup();
public void run() {
while (true) {
try {
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();
this.selector.select();
Iterator selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
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();
this.readBuffer.clear();
int numRead;
try {
numRead = socketChannel.read(this.readBuffer);
} catch (IOException e) {
key.cancel();
socketChannel.close();
return;
if (numRead == -1) {
key.channel().close();
key.cancel();
return;
this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
private void handleResponse(SocketChannel socketChannel, byte[] data,
int numRead) throws IOException {
byte[] rspData = new byte[numRead];
System.arraycopy(data, 0, rspData, 0, numRead);
RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
if (handler.handleResponse(rspData)) {
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);
while (!queue.isEmpty()) {
ByteBuffer buf = (ByteBuffer) queue.get(0);
socketChannel.write(buf);
if (buf.remaining() > 0) {
break;
queue.remove(0);
if (queue.isEmpty()) {
key.interestOps(SelectionKey.OP_READ);
private void finishConnection(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
try {
socketChannel.finishConnect();
} catch (IOException e) {
System.out.println(e);
key.cancel();
return;
key.interestOps(SelectionKey.OP_WRITE);
private SocketChannel initiateConnection() throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel
.connect(new InetSocketAddress(this.hostAddress, this.port));
synchronized (this.pendingChanges) {
this.pendingChanges.add(new ChangeRequest(socketChannel,
ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
return socketChannel;
private Selector initSelector() throws IOException {
return SelectorProvider.provider().openSelector();
public static void main(String[] args) {
try {
System.out.println ("the host name is " + args[0]);
NioClient client = new NioClient(
InetAddress.getByName(args[0]), 4444);
Thread t = new Thread(client);
t.setDaemon(true);
t.start();
RspHandler handler = new RspHandler();
client.send(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
.getBytes(), handler);
handler.waitForResponse();
} catch (Exception e) {
e.printStackTrace();
}

Similar Messages

  • Wierdness with NIO socket on Solaris 2.10 part I I

    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 {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    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));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    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();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    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();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    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);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }Edited by: LuriRon on Mar 16, 2009 10:42 AM

    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 {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    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));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    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();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    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();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    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);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }Edited by: LuriRon on Mar 16, 2009 10:42 AM

  • NIO sockets

    Hello,
    Im having difficulty understanding the WRITE issue of nio sockets. Ive read most of the nio-related posts on this forum but I still cant figure it out. Ive also looked at some examples by PkWooster but they seems really complicated.
    I have a server which accepts connections and echos messages to all clients. Everything works fine except my client cannot write to the server. I know I need to switch back and forth between Op interests since they can block the cpu if set incorrectly but I dont really understand what to set when. Since my server seems to be working fine Ill post my Clients code:
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.net.InetSocketAddress;
    import java.util.*;
    import java.nio.charset.*;
    public class GameClient implements Runnable {
      Game game;
      SocketChannel sc;
      ByteBuffer buffer;
    Selector selector;
    ByteBuffer sendBuffer=null;
        String host = "192.168.1.102";
        int port = 8888;
    private CharsetDecoder asciiDecoder;
    private CharsetEncoder encoder;
    private LinkedList sendQ = new LinkedList();
    SelectionKey sk;
    LinkedList invocations;
    public GameClient (Game g) {
    game = g;
        buffer = ByteBuffer.allocateDirect(1024);
              Charset charset = Charset.forName("ISO-8859-1");
              asciiDecoder = charset.newDecoder();
              encoder = charset.newEncoder();
    game.CharMSGArrival("Starting...");  // transfers data to the game thread
    public void run(){
    try{
        // Create a nonblocking socket channel and connect to server.
        sc = SocketChannel.open();
        sc.configureBlocking(false);
    game.CharMSGArrival("Connecting to server..."+"\n");
        InetSocketAddress addr = new InetSocketAddress(host, port);
        sc.connect(addr);    // Nonblocking
        while (!sc.finishConnect()) {
    game.CharMSGArrival("I am waiting ..."+"\n" );
    game.CharMSGArrival("Connection acqired"+ "\n" );
        // Send initial message to server.
        buffer.put((new Date().toString()+ "\n").getBytes());
        buffer.flip();
        sc.write(buffer);
        // Create a new selector for use.
        selector = Selector.open();
        // Register the socket channel with the selector.
        sk = sc.register(selector, SelectionKey.OP_READ);
        while (true) {
            //System.out.println("Listening for server on port " +
             //                   remotePort);
            // Monitor the registered channel.
            int n = selector.select();
            if (n == 0) {
                continue;   // Continue to loop if no I/O activity.
            // Get an iterator over the set of selected keys.
            Iterator it = selector.selectedKeys().iterator();
            // Look at each key in the selected set.
            while (it.hasNext()) {
                // Get key from the selected set.
                SelectionKey key = (SelectionKey) it.next();
                // Remove key from selected set.
                it.remove();
                // Get the socket channel from the key.
                SocketChannel keyChannel = (SocketChannel) key.channel();
                // Is there data to read on this channel?
                if (key.isReadable()) {
                    replyServer(keyChannel);
                if (key.isWritable()) {
                    doSend();
           } catch (IOException ioe) {
      private void replyServer(SocketChannel socketChannel)
                          throws IOException {
        // Read from server.
    buffer.flip( );
        int count = socketChannel.read(buffer);
        if (count <= 0) {
            // Close channel on EOF or if there is no data,
            // which also invalidates the key.
            socketChannel.close();
            return;
    buffer.flip( );
    String str = asciiDecoder.decode(buffer).toString( );
         game.CharMSGArrival(str);
    public void doSend(){
    sk.interestOps(SelectionKey.OP_WRITE);     
    if(sendBuffer != null)write(sendBuffer);
    writeQueued();     
    public void trySend(String text){ // this method is invoked when a send buttong is pressed in the 'game' thread
              sendQ.add(text);     // first put it on the queue
              writeQueued();          // write all we can from the queue
         private void writeQueued()
              while(sendQ.size() > 0)     // now process the queue
                   String msg = (String)sendQ.remove(0);
                   write(msg);     // write the string
    private void write(String text)
              try
              ByteBuffer buf = encoder.encode(CharBuffer.wrap(text));
                   write(buf);
              catch(Exception e){e.printStackTrace();}
             * write out a byte buffer
         private void write(ByteBuffer data)
              SocketChannel scc = (SocketChannel)sk.channel();
              if(scc.isOpen())
                   int len=0;
                   if(data.hasRemaining())
                        try{len = sc.write(data);}
                        catch(IOException e){e.printStackTrace(); //closeComplete();
                   if(data.hasRemaining())     // write would have blocked
    game.CharMSGArrival("write blocked"+"/n");
                        //writeReady = false;
         sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);     // select OP_WRITE
                        sendBuffer = data;          // save the partial buffer
                   else {sendBuffer = null;
    sk.interestOps(SelectionKey.OP_READ);     }
              else game.CharMSGArrival("write closed"+"/n");
    }

    public void doSend(){
    sk.interestOps(SelectionKey.OP_WRITE);     
    if(sendBuffer != null)write(sendBuffer);
    writeQueued();     
    }This method makes no sense. You only get into it if the key is writable, which means it is already registered for OP_WRITE, so why would you register it again?
    Also you're frequently ignoring the result of many write calls, of which you have too many.
    See the thread 'Taming the NIO circus': http://forum.java.sun.com/thread.jspa?threadID=459338,
    ignoring all the contributions except those by pkwooster and me.
    I'm not that crazy about Mina myself. It has its own buffer classes and it quietly uses threads, i.e. missing the entire point of NIO.

  • Selector thread in JSSE with NIO works nor parallely?

    Hi,
    I am now studying JSSE with NIO. Most of the codes are that I looked, used the Selectable Non blocking IO model. Selector thread contains many keys(keys == client sockets nearly)
    The Selector object maintains a set of selected keys and just one key is processed at a given time in a server program. So, there is no parallel work. I wonder why this keys are not processed parallely, not in batch process model in one thread?

    wow, this reply enlightens me.I have a question for you.
    here is a samle run method of runnable selector class.
    public void run() {
        while (true) {
          doPendingTasks();
          if (closeRequested) {
            return;
          int selectedKeys = 0;
          try {
            selectedKeys = selector.select();
          } catch (IOException ioe) {      
            ioe.printStackTrace();
            continue;
          if (selectedKeys == 0) {
            continue;
          Iterator it = selector.selectedKeys().iterator();
          while (it.hasNext()) {
            SelectionKey sk = (SelectionKey)it.next();
            it.remove();
            try {
              int readyOps = sk.readyOps();
              sk.interestOps(sk.interestOps() & ~readyOps);
              SelectorHandler handler =
                 (SelectorHandler) sk.attachment();         
              if (sk.isAcceptable()) {
                ((AcceptSelectorHandler)handler).handleAccept();
              } else if (sk.isConnectable()) {     
                ((ConnectorSelectorHandler)handler).handleConnect();           
              } else {
                ReadWriteSelectorHandler rwHandler =
                  (ReadWriteSelectorHandler)handler;              
                if (sk.isReadable()) {               
                  rwHandler.handleRead();             
                if (sk.isValid() && sk.isWritable()) {
                  rwHandler.handleWrite();                             
            } catch (Throwable t) {
              Shutdown();
              t.printStackTrace();
              return;
      }in this code every operation is managed by handler named "handleXXX".for example "handleRead" does reading job and also informs the side(client or server) for the data read.
    public void handleRead() {
        try {     
          int readBytes = channel.read(inBuffer);     
          if (readBytes == -1) {
            // Closing channel...
            close();
            side.socketDisconnected(this);
            return;
          inBuffer.flip();
          processInBuffer(); //if there is parts that belongs to more than one packet, seperate them and inform side(client/server)
        } catch (IOException ex) {
          side.socketException(this, ex);
          close();
      }Finally my question is if this approach is wrong.if not ,it takes more than zero time,doesn't it?
    If it is wrong , what approach do you suggest about handling operations?
    Thanks.

  • Experience with NIO client servers

    Dear Forum
    I am going to build a xml socket server and would like to use NIO rather than multi threadeding.
    What the server will do is accept client connections and run them on their own thread, these clients will then be able to send/recieve data in xml and also make simple queries to a mysql database.
    I have developed a similar system using conventional thread methods but not with NIO, the main problem that I have is i cannot see an example where a client connects a new thread is started for that client and then its reference is stored on the server allowing messages to be sent by iterating through the client vector. Is this the same for NIO?
    Any suggestions or pearls of wisdom would be great..
    Thankyou..

    If your application is basically multithreaded you are better off using the stream based sockets. If you insist on using NIO, I've posted information on multiple threads and NIO in Taming the NIO Circus. You biggest problems will come from the fact that interestOps and register block if a select is active. This forces you do do those all from the thread that does the select. You need to use a queue. Also NIO doesn't support SSL at present, maybe in 1.5.

  • Right way to communicate with a socket server (TCP/IP)

    Hi,
    I used to write data from my J2ME socket client to a J2EE socket server with writeUTF(). In this way I can send (and receive) directly Strings.
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?
    Just to know if I'm completely wrong....and if I gonna have unsolicited issues ...
    Thanks..

    AdrienD wrote:
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?No, it is not. Read the writeUTF api docs, and you'll know why!
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?There is answer to this question. it al depends on what data gets send where, how often, and how large..

  • Problem with native ldapsearch in Solaris 10

    Hi all,
    someone could tell me please why native ldapsearch in Solaris 10 do not work with SSL connection when same command comes with Sun Directory Server 5.2 works perfectly ?
    With native ldapsearch in Solaris 10, I get the error message "Can't contact LDAP server":
    # /bin/ldapsearch -v -h ldapserver -p 636 -Z -P /var/ldap -b dc=exemple,dc=fr -s base objectclass=\*
    ldap_init( ldapserver, 636 )
    filter pattern: objectclass=*
    returning: ALL
    filter is: (objectclass=*)
    ldap_search: Can't contact LDAP server
    When, on the same host, on which Directory server is installed, there's no problem:
    # /var/opt/mps/serverroot/shared/bin/ldapsearch -v -h ldapserver -p 636 -Z -P /var/ldap -b dc=exemple,dc=fr -s base objectclass=\*
    ldap_init( exemple, 636 )
    ldaptool_getcertpath -- /var/opt/mps/serverroot/alias
    ldaptool_getkeypath -- /var/opt/mps/serverroot/alias
    ldaptool_getdonglefilename -- (null)
    filter pattern: objectclass=*
    returning: ALL
    filter is: (objectclass=*)
    version: 1
    dn: dc=exemple,dc=fr
    nisDomain: exemple.fr
    objectClass: top
    objectClass: domain
    objectClass: nisDomainObject
    1 matches
    What can I do to bind to ldap server with SSL connection from an ordinary work station?
    Thank you in advance.
    Dra

    Hi :
    "The /usr/bin/ldapsearch is an old version that does not support the "-Z" and "-P" flags to test SSL connection on port 636, use the ldapsearch command from SUN DS5.0/5.1 that comes bundled with Solaris9 and usually installed at /usr/iplanet/ds5 (DS5.0/5.1) or /var/Sun/mps (DS5.1/5.2) or /var/opt/mps/serverroot (DS5.2)"
    Source : http://forums.sun.com/thread.jspa?threadID=5089467
    Hope this can help,
    Regards,
    Groucho_fr

  • Problem with the socket and the standard output stream

    Hy, I have a little problem with a socket program. It has the server and the client. The problem is that the client at one point in the program, cannot print messages in the console.
    My program does the next: the server waits connections, when a client connects to it, the server gets outputstream to the socket and writes two strings on it. Meanwhile, the client gets the inputstream to the socket and reads on it with a loop the two strings written by the server . The strings are printed by the client in the console. The problem starts here; once the read strings are printed ,I mean, after the loop, there are other System.out.println in the client but the console doesnt print anything . It curious that only when I comment on the server code the line that says: "br.readLine()" just before the catch, the client prints all the System.out.println after the loop but why?
    Here is the code:
    Server code:
    public class MyServerSocket {
    public MyServerSocket() {
    try{
    ServerSocket server= new ServerSocket(2000);
    System.out.println("servidor iniciado");
    Socket client=server.accept();
    System.out.println("Client connected");
    OutputStream os=client.getOutputStream();
    PrintWriter pw= new PrintWriter(os);
    String cadena1="cadena1";
    String cadena2="cadena2";
    pw.println(cadena1);
    pw.println(cadena2);
    pw.flush();
    InputStream is=client.getInputStream();
    InputStreamReader isr= new InputStreamReader(is);
    BufferedReader br= new BufferedReader(isr);
    br.readLine(); //If a comment this line, the client prints after the loop, all the System.out....
    catch (IOException e) {
    // TODO: handle exception
    public static void main(String[] args) {
    new MyServerSocket
    Client code:
    public class MyClientSocket {
    public MyClientSocket () {
    try{
    Socket client= new Socket("localhost",2000);
    InputStream is=client.getInputStream();
    InputStreamReader isr= new InputStreamReader(is);
    BufferedReader br= new BufferedReader(isr);
    String read;
    while((read=br.readLine())!=null){
    System.out.println(read);
    //These messages are not printed unless I comment the line I talked about in the server code
    System.out.println("leido");
    System.out.println("hola");
    }catch (IOException e) {
    public static void main(String[] args) {
    new MyClientSocket
    }

    You are right but with this program the loop ends. As you see, the first class, the Server, writes to the socket one text file. The second class, the client, reads the text file in his socket written by the server and writes it to a file in his machine.
    NOTE: The loop in the client ends and the server doesnt make any close() socket or shutdownOutput() .
    public class ServidorSocketFicheromio {
         public ServidorSocketFicheromio() {
    try{
         ServerSocket servidor= new ServerSocket(2000);
         System.out.println("servidor iniciado");
         Socket cliente=servidor.accept();
         System.out.println("cliente conectado");
         OutputStream os=cliente.getOutputStream();
         PrintWriter pw= new PrintWriter(os);
         File f = new File("c:\\curso java\\DUDAS.TXT");
         FileReader fr= new FileReader(f);
         BufferedReader br= new BufferedReader(fr);
         String leido;
         while((leido=br.readLine())!=null){
              pw.println(leido);
         pw.flush();
         }catch (IOException e) {
         * @param args
         public static void main(String[] args) {
              new ServidorSocketFicheromio();
    public class ClienteSocketFicheromio {
         public ClienteSocketFicheromio() {
    try{
         Socket cliente= new Socket("localhost",2000);
         File f = new File("G:\\pepe.txt");
         FileWriter fw= new FileWriter(f);
         PrintWriter pw= new PrintWriter(fw);
         InputStream is=cliente.getInputStream();
         InputStreamReader isr= new InputStreamReader(is);
         BufferedReader br= new BufferedReader(isr);
         String leido;
         while((leido=br.readLine())!=null){
              pw.println(leido);
              System.out.println(leido);
              System.out.println("leido");
              System.out.println("hola");
              pw.flush();
         }catch (IOException e) {
         public static void main(String[] args) {
         new ClienteSocketFicheromio();/
    }

  • [svn] 1720: Bugs: LCDS-304 - Authentication not working in all cases when using security constraint with NIO endpoints .

    Revision: 1720
    Author: [email protected]
    Date: 2008-05-14 14:50:06 -0700 (Wed, 14 May 2008)
    Log Message:
    Bugs: LCDS-304 - Authentication not working in all cases when using security constraint with NIO endpoints.
    QA: Yes
    Doc: No
    Details:
    Update to the TomcatLoginCommand to work correctly with NIO endpoints.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/LCDS-304
    Modified Paths:
    blazeds/branches/3.0.x/modules/opt/src/tomcat/flex/messaging/security/TomcatLoginCommand. java

    Revision: 1720
    Author: [email protected]
    Date: 2008-05-14 14:50:06 -0700 (Wed, 14 May 2008)
    Log Message:
    Bugs: LCDS-304 - Authentication not working in all cases when using security constraint with NIO endpoints.
    QA: Yes
    Doc: No
    Details:
    Update to the TomcatLoginCommand to work correctly with NIO endpoints.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/LCDS-304
    Modified Paths:
    blazeds/branches/3.0.x/modules/opt/src/tomcat/flex/messaging/security/TomcatLoginCommand. java

  • NIO sockets - cant get it to block!

    Hi,
    I'm trying to use NIO sockets in a program which sends data to a socket on another machine. I want it to block so that it must wait for a response before it continues. However this doesnt happen! I used Ethereal to see the packets being sent and recieved and the socket clearly doesnt block. Am I correct in thinking that NIO sockets are configured to block by default? I even tried using the configureBlocking(true) method to make sure but it still didnt block. Can anyone shed some light onto why this could be happening? Has this happened to anyone else?
    Cheers

    thomfost wrote:
    I've tried using regular I/O but its a bit too slow for what I need, im trying to see if using NIO improves this.Well you can stop now because it won't. NIO, as mentioned, is non-blocking IO, so a thread that is titled "NIO sockets - cant get it to block!" is not ultra promising. More importantly NIO will not make your IO "faster" by some magic. That's not what it does. It helps you write programs that scale because you don't need to have a thread dedicated to every client who connects to your system.
    At any rate you have multiple mistakes here which suggest the other slowness problem you refer to is a logical problem in your code. So why don't you tell us about that instead?

  • Identifying and managing clients in nonblocking NIO socket programming

    Here's my beef. When I write a Server using a thread for every new connection that comes in, I can remember everything for each client in its respective thread. I can have a table entry in a MYSQL database for each client which each thread can look up by a remembered id. I can direct packets from a different application to a specific client by passing a message to the thread associated with the client. But, in this implementation, the client-server setup will need to have a master-slave relationship where one is always reading, and can talk on the network only in response.
    I like the NIO selector way of doing things, but I do not get a memory method to deal with specific clients. How do I, for example,
    direct packets to a specific client.?
    recognize incoming packet info and make sense of its context in relation to past messages to and from the same client?
    maintain one-to-one correspondence between a MYSQL database table entry and a specific client?
    Could somebody explain this to me how I can maintain a client environment, and a client state machine with memory?
    Thanks
    Anil

    cloud9ine wrote:
    Here's my beef. When I write a Server using a thread for every new connection that comes in, I can remember everything for each client in its respective thread. I can have a table entry in a MYSQL database for each client which each thread can look up by a remembered id. I can direct packets from a different application to a specific client by passing a message to the thread associated with the client. But, in this implementation, the client-server setup will need to have a master-slave relationship where one is always reading, and can talk on the network only in response.
    I like the NIO selector way of doing things, but I do not get a memory method to deal with specific clients. How do I, for example,
    direct packets to a specific client.?
    recognize incoming packet info and make sense of its context in relation to past messages to and from the same client?
    maintain one-to-one correspondence between a MYSQL database table entry and a specific client?
    Could somebody explain this to me how I can maintain a client environment, and a client state machine with memory?
    Thanks
    AnilYou will use select() and SelectionKey when you deal with NIO. The SelectionKey has an attach method that you can use to associate the client with something, e.g. a session. Your Session class can contain all that you now have in your thread.
    Kaj

  • Threads with http socket

    Are there any good tutorials that teaches multithreading with http sockets?

    Topic: IDLE Time for Java Application not SYSTEM Idle Hi I am Krishna , I want to calculate idle time for an application.That is , if user1 uses the application for example called "yahoo site" for checking mails , then after 10 mins he went to outside , from 11th min the status of application should show (Like Yahoo messenger after certail time it shows idle time ) in another ADMINJSP page for Admins that how much this user1 idle say.. : 1 min idle 2 min idle .... .... 10 min idle Now user1 comes and now clicks on application . then ADMINJSP page should show total IDLE time (10 mins idle). And he again after 15 mins he went some where from 16th min the status of the application should show in ADMINJSP page.If user1 left the application like that then the application should be idle for 1 hour i.e 1 min idle 2 min idle ... ... 59 mins idle 60 mins idle Time Up -- Session Expired then he has to login again. So the above is the issue --------------------------------------------------------------------------- What i have done ..................issssssssssssss ------------------------------------------------------------------------- I have taken time for last request by using getLastAccessedTime() I have taken present time System.currentTimeMills() Taking the difference we will get the idle time . But the problem here is When user1 click on any page only this calcuting will be done and showing to ADMINJSP because getLastAccessedTime works only when any requests comes , but we dont want like that , we want the application without any requests from user1 the application should show idle for 1 min , 2 mins , 3 mins...so on upto user1 uses the application then the time should be normal. I have also tried all the EVENTS classes in HttpSessionBinding like valueunbound()...or sessiondestroy() etc. Can any one please help me by giving any CODE.If you need more information plz ask me Plz plz plz plz this is very urgent plz can any please send me the CODE , ihave tried this very hard but no idea how to do? long startTime = session.getLastAccessedTime(); long stopTime = System.currentTimeMillis(); long diffTimeInSecs = (stopTime - startTime) / 1000 ; gives idle time for every request Regards Krishna

  • ANOTHER Java NIO Socket Bug??

    I think I'm being really dense here but for the life of me, I can't get this code to work properly. I am trying to build a NIO socket server using JDK 1.4.1-b21. I know about how the selector OP_WRITE functionality has changed and that isn't my problem. My problem is that when I run this code:
    if (key.isAcceptable()) {
         System.out.println("accept at " + System.currentTimeMillis());
         socket = server.accept();
         socket.configureBlocking(false);
         socket.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    if (key.isWritable()) {
         SocketChannel client = (SocketChannel)key.channel();
         System.out.println("write at " + System.currentTimeMillis());
    if (key.isReadable()) {
         SocketChannel client = (SocketChannel)key.channel();
         readBuffer.clear();
         client.read(readBuffer);
         System.out.println("read at " + System.currentTimeMillis());
    }the isWritable if statement will always return (which is fine) and the isReadable if statement will NEVER return (which is most certainly NOT FINE!!). The readBuffer code is there just to clear out the read buffer so isReadable is only called once per data sent.
    This SEEMS to be a bug in how the selector works? I would expect to see isReadable return true whenever data is sent, but that is not the case. Now here is the real kicker ;) Go ahead and change this line:
    socket.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);to this:socket.register(selector, SelectionKey.OP_READ);And now it appears that isReadable is running as expected?! To let people run this code on their own, I have uploaded a copy of the entire java file here:
    http://www.electrotank.com/lab/personal/mike/NioTest.java
    Please forgive the code, it's just the smallest test harness I could make and much of it is lifted from other posts on this forum. You can test this by using Telnet and connecting to 127.0.0.1:8080. You can test the isReadable piece by just typing in the Telnet window.
    Someone else has listed something as a bug in the Bug Parade, but the test case is flawed:
    http://developer.java.sun.com/developer/bugParade/bugs/4755720.html
    If this does prove to be a bug, has someone listed this already? Is there a nice clean workaround? I'm getting really desperate here. This bug makes the NIO socket stuff pretty unusable. Thanks in advance for the help!!
    Mike Grundvig
    [email protected]
    Electrotank, Inc.

    Yeah, isReadable crashed for me too.
    My solution was to not call it. I set up two selectors for the two operations I wanted notifying (accept and read) and used them independently in different threads. The accept thread passes them over to the read thread when they're accepted.
    This way I don't need to call isReadable since it is bound to be readable otherwise it wouldn't have returned, as read is the only operation I'm being notified about.
    --sam                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • [svn:bz-trunk] 16395: Bug: #2621264 [Regression] Small messages not working with NIO-HTTP endpoints in LCSD/trunk.

    Revision: 16395
    Revision: 16395
    Author:   [email protected]
    Date:     2010-06-02 05:00:56 -0700 (Wed, 02 Jun 2010)
    Log Message:
    Bug: #2621264 Small messages not working with NIO-HTTP endpoints in LCSD/trunk.
    QA: Yes
    Doc: No
    Checkintests: Pass
    Details: This is the BlazeDS side of the fix. This wasn't a regression, it probably never worked correctly. So, in the scenario where there's a Producer and a Consumer, and Producer sends a message for the Consumer, there are 2 messages from the server. The ACK message for Producer's send, and the actual message Consumer receives. I found that the ACK message was in small form, but the actual message was not in streaming messages. This was because we never really tried to convert streamed messages into small messages before.
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/endpoints/BaseStreamingHTTPEndpoint.java
        blazeds/trunk/modules/core/src/flex/messaging/endpoints/StreamingAMFEndpoint.java
        blazeds/trunk/modules/core/src/flex/messaging/endpoints/StreamingHTTPEndpoint.java

  • How to install Apache Web Server with PHP on Sun Solaris Sparc machine

    Hi,
    We are trying to install the Apache Web Server and the PHP package on a Sun Solaris Sparc machine running on SunOS 5.8. We are having compilation problems with the source code of both these packages.
    Does anybody know if there are ready solaris packages for Apache and PHP available from where we can download and install instead of source code compilation?
    Or any instructions / things to watch for when installing Apache with PHP (if anybody has tried installing Apache with PHP on Sun Solaris earlier) is most welcome.
    Thanks,
    Harish

    Apache should be bundled along with Solaris check in "/var/apache" in Solaris 8 and Solaris 9
    php is available at www.php.net
    I found an old document for installing PHP maybe this will help.
    Cheers
    -Dhruva
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++Installing PHP 3.x for Apache 1.x.x on Solaris
    Introduction
    This document describes how to install PHP for Apache on Solaris.
    You should have Apache installed before trying to install PHP.
    If you want to use PHP with MySQL then you must install MySQL first.
    Before we Begin
    1. These instructions assume that you have Apache installed according to instructions.
    Getting PHP
    1. You must be logged in as root to perform this installation.
    su root
    2. I save all my downloads in:
    /usr/local/dist
    If you don't already have one, you may need to create that directory now:
    mkdir /usr/local/dist
    3. You can get PHP 3.0.14 from here(www.php.net).
    cd /usr/local/dist
    ftp ftp.php.net
    cd pub/distributions
    bin
    get php-3.0.14.tar.gz
    bye
    Installing PHP
    1. We will install PHP in /usr/local/build, but use a tricky tar command
    to do it in on hit from the download directory:
    cd /usr/local/dist
    tar xvfz php-3.0.12.tar.gz -C ../build
    Compiling PHP
    1. First let's get where the action is:
    cd /usr/local/build/php-3.0.14
    2. You now have 3 options:
    * Simple PHP install without MySQL - goto step 3
    * Simple PHP install with MySQL - goto step 4
    * Custom PHP install - goto step 5
    3. Simple PHP install without MySQL. Next, jump to step 6.
    ./configure --with-apache=../apache_1.3.12
    4. Simple PHP install with MySQL. MySQL must be installed before you can configure PHP to use it. I recommend that MySQL should always be reachable with /usr/local/mysql. Even if you install it else where you
    should create a symbolic link from /usr/local/mysql. Otherwise the compiler can have problems finding the mysqlclient library. The command
    should look like this:
    ./configure with-mysql=/usr/local/mysql with-apache=../apache_1.3.12
    Next, jump to step 6.
    5. Custom PHP install. Take a look at the available configuration directives by using this command:
    ./configure --help
    6. Now we can make the PHP executable. This may take a while.
    make
    7. Now we install the PHP module with:
    make install
    Adding the PHP Module to Apache
    1. Now we have to setup Apache to include the PHP module:
    cd ../apache_1.3.12
    2. Re-configure Apache to use the PHP module. You should use your previous Apache configure command along with the PHP activate module directive.
    You can see your previous Apache configure command by doing:
    cat config.status
    You can configure Apache using the previous command with the added PHP module by doing:
    ./config.status --activate-module=src/modules/php3/libphp3.a
    If you used the simple Apache install from instructions the command will look like this:
    ./configure prefix=/usr/local/apache activate-module=src/modules/php3/libphp3.a
    3. Make and install Apache with PHP enabled:
    make
    4. We need to stop the server before installing the files:
    /usr/local/apache/bin/apachectl stop
    5. Now we can install the new binaries:
    make install
    6. Start apache again (now running the new php enabled version):
    /usr/local/apache/bin/apachectl start
    Setting Up PHP
    1. We have to tell Apache to pass certain file extensions to PHP. We do this in Apache's httpd.conf file.
    cd /usr/local/apache/conf
    2. Edit the httpd.conf file. If you do a search for php you will find a couple of commented out lines telling Apache to use the PHP module. You should uncomment them to look like this.
    AddType application/x-httpd-php3 .php3
    AddType application/x-httpd-php3-source .phps
    3. I prefer to use the extension .phtml, you can use whatever extension you like (even .html) by adding lines to httpd.conf like this:
    AddType application/x-httpd-php3 .phtml
    Check that it Works
    1. We have to restart Apache to make these changes take effect on the running server.
    cd /usr/local/apache/bin
    ./apachectl restart
    2. Apache should now be running with PHP enabled. The server version should include PHP/3.0b2.
    ./apachectl status
    Apache Server Status for dev.synop.com
    Server Version: Apache/1.3.9 (Unix) PHP/3.0.12
    Server Built: Oct 25 1999 00:37:07
    3. Now it is time to test PHP with a page. The simplest thing to do is create a page called test.php3. My file is here. This file contains the
    following text:
    <?php phpinfo(); ?>
    4. Point your browser at this file on the virtual host which you used:
    http://localhost/test.php3

Maybe you are looking for