About NIO non-blocking socket write method behavior

Hi all -
I hope anyone could help in this issue.
Assume you create a NIO socket and configure its channel in non blocking mode:
channel.configureBlocking(false);
then you write a byte buffer into it:
int sentBytesNum = channel.write(byteBuffer);
What are the possibilities of sentBytesNum value? I am sure of two possibilities, which are:
- all data sent so sentBytesNum equals byteBuffer data size (limit minus position before sending) (after sending the limit and position of byteBuffer are the same)
- no data is sent so sentBytesNum is zero and byteBuffer limit and postion did not change, so we shall use a write selector to test when the channel will be ready for write to write the data.
What I am not sure about and need someone to confirm is the third possibility:
- only a part of data is sent (according to the available free space of socket output buffer) so sentBytesNum is more than zero but less than data size and byteBuffer position is advanced by the value of sentBytesNum, might this possibility happen??
If yes, so we should manage to hold the non sent part of byteBuffer till the channel becomes ready for write (we can know that using write selector) so we can write it to channel???
Thanks for help,
Rocka

Yes, case three can occur. The usual NIO write loop looks like this:
int count = 0;
while (buf.position() > 0)
  buf.flip();
  count = ch.write(buf);
  buf.compact();
  if (count == 0)
    break;
}This will run until buf.position() == 0 or count == 0. If the partial write case happens it will loop one more time and probably get a 0 count.
At the end of the loop, if buf.position() > 0 there is still unwritten data and at this point you should register for OP_WRITE and return to the selector. Otherwise if there is no data unwritten you should deregister OP_WRITE as you have nothing to write and aren't interested in the event any longer.
If you are reading something and writing at the same time the logic goes like this:
while (inch.read(buf) >= 0 || buf.position() > 0)
  // etc
}This will read until EOF occurs and either buf.position() is zero or a zero length write occurred.

Similar Messages

  • Detecting When a Non-Blocking Socket Is Closed by the Remote Host

    Hi,
    Using NIO non blocked sockets how do I detect when a Non-Blocking Socket Is Closed by the Remote Host?
    What I have read is:
    The only way to detect that the remote host has closed the connection is to attempt to read or write from the connection. If the remote host properly closed the connection, read() will return -1. If the connection was not terminated normally, read() and write() will throw an exception.
    I have written a server test program using NIO and an applet connecting to the server program via sockets.
    When I after a successful connection shuts down the browser following happens: The code below comes in an endless loop though mySelector.select returns 0 every time. (The selector is registered for OP_READ). size = 1.
    while (true) {
    int n = mySelector.select();
    int size = mySelector.keys().size();
    if (n == 0) continue;
    Is this an expected result?
    How do I get to know what client has lost connection?
    My environment:
    W2000
    java 1.4.1 build 1.4.1_01-b01
    Browser used: IE 5.0
    Many thanks for your help on this matter!
    Regards Magnus Wistr�m

    What you're doing looks OK to me.
    I wonder whether your thread is being interrupted by Thread.intterupt() somewhere. Try putting a Thread.interrupted() before the select call.
    Sylvia.

  • 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.

  • NIO Non-Blocking Server not Reading from Key

    I have created a NIO non blocking server (below) and it will not pick up any input from the client.... My log doesnt even show that it enters the readKey() method, so it must be something before. Any help would be appreciated.
    Scott
    package jamb.server;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.ClosedChannelException;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.logging.Logger;
    import java.util.prefs.Preferences;
    import jamb.server.client.Client;
    public class Server {
            private Selector selector;
            private ServerSocketChannel serverChannel;
            private static Logger logger = Logger.getLogger("jamb.server");
            private static Preferences prefs =  Preferences.systemRoot().node("/jamb/server");
            public void init() {
                    logger.entering("jamb.server.Server", "init");
                    //Get a selector...
                    try {
                            selector = SelectorProvider.provider().openSelector();
                            //Open the SocketChannel and make it non-blocking...
                            serverChannel = ServerSocketChannel.open();
                         serverChannel.configureBlocking(false);
                            //Bind the server to the port....
                            int port = prefs.getInt("Port", 4000);
                            logger.config("Server configured on port " + port + " (default: 4000)");
                         InetSocketAddress isa = new InetSocketAddress(
                                    InetAddress.getLocalHost(), port);       
                         serverChannel.socket().bind(isa);
                    } catch (IOException ioe) {
                            logger.severe ("IOException during server initialization!");
                    logger.exiting("jamb.server.Server", "init");
            public void run() {
                    logger.entering("jamb.server.Server", "run");
                    int bufferSize = prefs.getInt("BufferSize", 8);
                    logger.config("Buffer size set to " + bufferSize + " (default: 8)");
                    SelectionKey acceptKey = null;
                    try {
                            acceptKey = serverChannel.register(
                                    selector, SelectionKey.OP_ACCEPT);
                    } catch (ClosedChannelException cce) {
                    try {
                            while (acceptKey.selector().select() > 0) {
                                    Set readyKeys = selector.selectedKeys();
                                    Iterator i = readyKeys.iterator();
                                    while (i.hasNext()) {
                                            //logger.finest("Processing keys...");
                                            //Get the key from the set and remove it
                                            SelectionKey currentKey = (SelectionKey) i.next();
                                            i.remove();
                                            if (currentKey.isAcceptable()) {
                                                    logger.finest("Accepting key...");
                                                    acceptKey(currentKey);
                                            } else if (currentKey.isReadable()) {
                                                    logger.finest("Reading key...");
                                                    readKey(currentKey, bufferSize);
                                            } else if (currentKey.isWritable()) {
                                                    //logger.finest("Writing key...");
                                                    writeKey(currentKey);
                    } catch (IOException ioe) {
                            logger.warning("IOException during key handling!");
                    logger.exiting("jamb.server.Server", "run");
            public void flushClient (Client client) {
                    try {
                            ByteBuffer buf = ByteBuffer.wrap( client.getOutputBuffer().toString().getBytes());
                            client.getChannel().write(buf);
                    } catch (IOException ioe) {
                            System.out.println ("Error writing to player");
                    client.setOutputBuffer(new StringBuffer());
            private void acceptKey (SelectionKey acceptKey) {
                    logger.entering("jamb.server.Server", "acceptKey");
                    //Retrieve a SocketChannel for the new client, and register a new selector with
                    //read/write interests, and then register
                    try {
                            SocketChannel channel =  ((ServerSocketChannel) acceptKey.channel()).accept();
                            channel.configureBlocking(false);
                            SelectionKey readKey = channel.register(
                                    selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE  );
                            readKey.attach(new Client(this, channel));
                    } catch (IOException ioe) {
                            System.out.println ("Error accepting key");
                    logger.exiting("jamb.server.Server", "acceptKey");
            private void readKey (SelectionKey readKey, int bufSize) {
                    logger.entering("jamb.server.Server", "readKey");
                    Client client = (Client) readKey.attachment();
                    try {
                            ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize);
                            int nbytes = client.getChannel().read( byteBuffer );
                            byteBuffer.flip();
                            Charset charset = Charset.forName( "us-ascii" );
                            CharsetDecoder decoder = charset.newDecoder();
                            CharBuffer charBuffer = decoder.decode(byteBuffer);
                            String text = charBuffer.toString();
                            client.getInputBuffer().append(text);
                            if ( text.indexOf( "\n" ) >= 0 )
                                    client.input();
                    } catch (IOException ioe) {
                            logger.warning("Unexpected quit...");
                            client.disconnect();
                    logger.exiting("jamb.server.Server", "readKey");
            private void writeKey (SelectionKey writeKey) {
                    //logger.entering("jamb.server.Server", "writeKey");
                    Client client = (Client) writeKey.attachment();
                    if (!client.isConnected()) {
                            client.connect();
                    //logger.exiting("jamb.server.Server", "writeKey");

    From my own expierence with the NIO (Under Windows XP/ jdk1.4.1_01); you can't seem to set READ and WRITE at the same time.
    The program flow I usually end up with for a echo server is:
    When the selector.isAcceptable(): accept a connection; register for READs
    In the read event; write the incoming characters to a buffer; register for a WRITE and add the buffer as an attachment.
    In the write event; write the data to the socket If all the data was written; register for a READ; otherwise register for another WRITE so that you can write the rest.
    Not sure if that the "proper" way; but it works well for me.
    - Chris

  • Easy way to non-blocked sockets

    Use JSSE and NIO for a quick way to implement non-blocking communications
    October 22, 2003
    Although SSL blocking operations -- in which the socket is blocked from access while data is being read from or written to -- provide better I/O-error notification than the non-blocking counterpart, non-blocking operations allow the calling thread to continue. In this article, the author will cover both the client and server side as he describes how to create non-blocking secure connections using the Java Secure Socket Extensions (JSSE) and the Java NIO (new I/O) library, and he will explain the traditional approach to creating a non-blocking socket, as well as an alternative (and necessary) method if you want to use JSSE with NIO.
    http://www-106.ibm.com/developerworks/java/library/j-sslnb.html?ca=dgr-jw03j-sslnb

    MORE IBM SPAM Previous discussion
    I find it interesting spam, but thats a matter of taste. If the OP was truly interested in "trying to get new information out there" he would answer the mulitple questions about NIO and especially NIO mixed with traditional Sockets and NIO vs Secure Sockets. These are all on ALT, NIO is of no interest to New to Java folk.
    Given their budget I think IBM could do a better job of publishing their research.

  • Non blocking sockets

    Hi All,
    Anybody have some idea about how to implement non blocking sockets using two threads/Can u help me with some sites where i can get more information in this topic.
    Regards
    Priya

    hi,
    you could have a look at the nonblocking io (nio) api's present in jdk1.4, that should do the trick. this link ought to get u started i suppose..
    http://developer.java.sun.com/developer/technicalArticles/releases/nio/
    hope this helps.
    cheerz
    ynkrish

  • Writing Java Non-Blocking Socket Server for  Winsock Client

    Hi.
    Im a newbie to Sockets. I need to write a Non-Blocking Socket server (using java.nio) that accepts connection and reads the data sent by WinSock clients, and write them to another winsock client. Its quite intriguing. How do I do that? Is it possible?
    Thanks in advance
    Arun

    Well, in traditional 4.2 BSD sockets, you'd fill up a set of filedescriptors of connections (an array of bits usually), and push that in the read parameter of a call to 'select'. Select then blocks until at least one of the file descriptors become available for reading, or writing if you also made an fd_set full of file descriptors (but you can usually write freely to a socket, so there is not much use for that). Then you start finding out which of these file descriptors have actually become available for reading, and you pass those to a bunch of worker-threads. The advantage is that your set of worker-threads can be quite small, while your number of connections can still be quite large (unless, of course, everyone of your clients start talking all at once, but that is no different from the one-socket-one-thread-model that java.net.* forces upon you).
    In java, the 'select' call is replaced by a call to java.nio.channels.Selector.select(); and then the fishing out of the selected stuff comes from java.nio.channels.Selector.selectedKeys().
    To add a thingy to a selector, use (for example) java.nio.channel.ServerSocketChannel.register(Selector, ops, att);
    whereby the ops parameter is the kind of action you'd like to select this channel for; SelectionKey.OP_READ etc..
    The workerthread bit is also easy to write, but I leave that to you as an exercise.

  • JDK 1.4 nio non-blocking connects don't finish

    I am working with the Linux version of JDK1.4, doing some testing of the
    non-blocking capability. The few tests that I have done have shown some
    strange results:
    - When opening a non-blocking connection to a server which has an
    announcement banner, say such as POP which gives something like:
    +OK pop3 server ready
    then connection seems to be OK and proceed through to completion.
    - When opening a non-blocking connection to a server which is silent, and
    expects me to start the conversation, such as contacting an HTTP server,
    then the Selector.select() never returns to allow me to finish the
    connection.
    Below is a test program which illustrates the problem for me.
    It attempts to open a non-blocking connection to www.yahoo.com on port 80.
    It then drops into a Selector.select() where I am waiting for the chance to
    catch the SelectionKey.OP_CONNECT event and finish connecting, and then send
    a simple HTTP GET request down the wire. That OP_CONNECT event
    never seems to arrive though, and I remain stuck in the select().
    'netstat -na' shows that I am in a connection established state.
    Any insight appreciated,
    -Steve M [email protected]
    ------------------>8 cut here 8<-----------------------
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.nio.*;
    import java.nio.channels.*;
    public class NoWorkee
    public static String GET_REQUEST = "GET / HTTP/1.0\r\n\r\n";
        static class Context
            String host;
            int    port;
            ByteBuffer request;
            public Context (String h, int p, ByteBuffer r)
            {host=h; port=p; request=r;}
    Selector sel = null;
    boolean keepGoing = true;
    public NoWorkee()
        throws IOException
        sel = Selector.open();
    public void add(String host, int port)
        throws IOException
        int ops = SelectionKey.OP_CONNECT;
        // create non-blocking socket, and initiate connect operation
        SocketChannel sc = SocketChannel.open();
        sc.configureBlocking(false);
        sc.connect(new InetSocketAddress(InetAddress.getByName(host), port));
        SelectionKey sk;
        try
            sk = sc.register(sel, ops);
            System.out.println ( "sc.register looks good connected=" +
                sc.isConnected() + ", isConnectionPending=" +
                sc.isConnectionPending());
            sk.attach(new Context(host, port, ByteBuffer.wrap(GET_REQUEST.getBytes())));
        catch (IOException x)
            x.printStackTrace();
            sc.close();
    public void run()
        throws IOException
        keepGoing = true;
        System.out.println ( "Selecting " + sel.keys().size() + " SelectKeys");
        while (keepGoing)
            final long before = System.currentTimeMillis();
            final int numReady = sel.select();
            //final int numReady = sel.select(1000);
            final long after = System.currentTimeMillis();
            System.out.println ( "Blocked " + (after-before) + " ms, numReady=" + numReady);
            if (numReady > 0)
                Set readyKeys = sel.selectedKeys();
                System.out.println ( "Selected keys size " + readyKeys.size());
                for (Iterator it = readyKeys.iterator(); it.hasNext();)
                    SelectionKey sk = (SelectionKey)it.next();
                    SocketChannel sockChan = (SocketChannel)sk.channel();
                    Context ctx = (Context)sk.attachment();
                    System.out.println ( "Servicing host " + ctx.host + " port "
                                 ctx.port);
    System.out.println ( "1");
                    if (sk.isConnectable())
                        if (sockChan.finishConnect())
                            System.out.println ( "Finished connecting success "
    + sockChan);
                            int ops = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
                            sk.interestOps (ops);
                        else
                            System.out.println ( "Could not finishConnect for "
                                sockChan);
                            sk.cancel();
                            sockChan.close();
    System.out.println ( "2");
                    if (sk.isAcceptable())
                        System.out.println ( "in sk.isAcceptable() block");
    System.out.println ( "3");
                    if (sk.isReadable())
                        System.out.println ( "in sk.isReadable() block");
                        byte rawBuff[] = new byte[32 * 1024];
                        ByteBuffer buff = ByteBuffer.wrap(rawBuff);
                        int numRead = -1;
                        while (0 < (numRead = sockChan.read(buff)))
                            System.out.println ( "numRead = " + numRead);
                            for (int i = 0; i < numRead; i++)
                                System.out.print((char)rawBuff);
    System.out.println ( "numRead = " + numRead);
    System.out.println ( "4");
    if (sk.isWritable())
    System.out.println ( "in sk.isReadable() block");
    int numWritten = -1;
    if (null != ctx.request)
    numWritten = sockChan.write(ctx.request);
    if (!ctx.request.hasRemaining())
    sk.interestOps(sk.interestOps() &
    ~SelectionKey.OP_WRITE);
    System.out.println ( "numWritten = " + numWritten);
    //else
    // service timeouts
    public static void main (String arg[])
    try
    NoWorkee bla = new NoWorkee();
    bla.add ("www.yahoo.com", 80);
    bla.run();
    catch (Exception e)
    e.printStackTrace();
    ------------------>8 cut here 8<-----------------------

    Just for the benefit of anyone who might be seeing the same problem, it looks like bug 4457776 accurately describes the problem that I was having above.
    I am downloading j2sdk-1_4_0-beta2-linux-i386-rpm.bin to see if that fixed it.
    Reference:
    http://developer.java.sun.com/developer/bugParade/bugs/4457776.html

  • Broken Pipe with Non-blocking Socket

    Hello,
    I write a Unix Agent who connect on a Windows Server with socket...
    Working well on Linux but on Solaris my problem is:
    -When my agent is running before server at connection all seems OK: Connect, Select and Getsockopt but when I try to send data I have always EPIPE Signal but I can receive datas from server !
    - When my agent is strarting after the server all it's Ok
    I don't unserstand this appears on Solaris SPARC 8 and Solaris 9 Intel ...
    Please Help is there something special with non-blocking sockets on Solaris ?
    Thanks

    Can't help you much but what I would recommend is that you
    insure that your pipes are opened for both read/write, even
    though you are only going to read or write from it. This insures
    that the pipe does not close down when you hit EOF.

  • Read Timeout on non-blocking sockets

    Hi,
    I was wondering if there is a way to specify a read timeout (like setSoTimeout for synchronous sockets) when using a non-blocking socket.
    I'd like to have the select() method return is a sockets timeout expires, puting in the selected key set the timedout socket and have it's read operation return -1, something like what happens when a socket is closed by the other side.
    The thing is I need this to be a timeout specific to each socket, thus the select(millis) isn't apropriate.
    Anyone knows of something like this?
    Thanks....

    Yeah, select() is the only thing built in for that, and you have to do the bookkeeping yourself. You would start something like forming the disjunction of the ready keys and the registered keys after each select, to get the unready keys, and then looking at their history to see how long they have been unready via a Map{key,Long(time)).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • UTL_TCP (blocking or non-blocking sockets mode)

    Hi for All,
    Please, someone knows if the UTL_TCP using blocking or non-blocking sockets mode? I did a search but can not find this information.
    Regards,

    Blocking only occurs when you attempt to read from the socket and there's no data to read. (in which case, the time out setting applies if specified)
    This is however not that robust in my experience. UTL_TCP provides a peek method (returns byte size of socket buffer) that tells you whether or not there is data for that socket. This enables you to verify that you read on that socket will not be a blocking call.
    I prefer using this method, as dealing with a timeout approach results in run-time behaviour issues (either a call waiting too long, or a call timing out too quickly).

  • Non Blocking Socket ans Session management

    All samples of Non Blocking socket use SelectionKey.attach( Object ob) to attach a partial message if the received data is incomplete. So far so good.
    Are we supposed to use the same approach for session management ( Keeping info on Username, password, timeout values, etc.)
    Thanks

    I disagree with your first statement. The attachment is normally a session object that contains user information, session state, and the ByteBuffer.

  • How to handle write errors in non blocking sockets

    Hi,
    I'm using sockets registered with a Selector for read operations. I've seen code examples that put the SocketChannel in non blocking mode before registering it with the selector, and in fact not doing so would cause an IllegalBlockingModeException to be thrown.
    My problem is that I can't handle write errors. The call to write() returns inmediately without throwing any exception. Even worse, when the network timeout expires the selector wakes up and I get an exception on read(). So I can't tell the difference between a real read error and a write error.
    What can I do? Is there a magic method I haven't heard about?
    Thanks

    ejp wrote:
    OK, so what happens is this: you write from your ByteBuffer; if there is room in the socket send buffer, the data is transferred and the transfer count is returned. (If there isn''t, the write returns zero and nothing has happened.) Your application code then continues. Meanwhile TCP is trying to send the data in the send buffer and get an ACK from the peer. If the peer is down as per your test, eventually those write attempts will time out. You will then get a connection reset exception on the next read or write.
    Even worse, when the network timeout expires the selector wakes upCorrect, to tell you there is an error condition pending. This is good, not bad.You're right. This way my program can know that something happened.
    But I still don't understand what the difference between a failed write() and a failed read() is. I mean, the error condition may appear during a send attempt, or it may appear after sending. In both cases I get an error when trying to read. How can my program know if data have been received by the other end?
    Do I have to implement ACK messages in the application level protocol??? It'd be nice if TCP could do this for me...

  • Non-blocking socket concurrent limitation?

    I have 2 socket program,one is server side used nio package with JDK1.4.1,the other is client used traditional socket,the client will initialize about 50
    threads trying to connect with server when starting,but only about 15
    can be accepted,these 2 program are runnning in the same computer which
    OS is win2000 professional PC.
    the followd is these code:
    please make a probe with them ,and tell me what's going on?
    server:
    package nio_select_demo;
    import java.io.*;
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.util.*;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    public class Server implements Runnable
    // The port we will listen on
    private int port;
    // A pre-allocated buffer for processing data
    private final ByteBuffer buffer = ByteBuffer.allocate( 16384 );
    private ByteBuffer resBuf = ByteBuffer.allocate( 128 );
    Selector selector;
    AddInfo test ;
    public Server( int port ) {
    this.port = port;
    // for (int i=0; i<threadnum; ++i) {
    new Thread( this ).start();
    test = new AddInfo();
    test.start();
    public void run() {
    try {
    // create a ServerSocketChannel
    ServerSocketChannel ssc1 = ServerSocketChannel.open();
    // ServerSocketChannel ssc2 = ServerSocketChannel.open();
    // Set it to non-blocking
    ssc1.configureBlocking( false );
    // Get the Socket connected to this channel, and bind it
    // to the listening port
    ServerSocket ss = ssc1.socket();
    InetSocketAddress isa = new InetSocketAddress( port );
    ss.bind( isa , 60 );
    // Create a new Selector for selecting
    selector = Selector.open();
    // Register the ServerSocketChannel, so we can
    // listen for incoming connections
    ssc1.register( selector, SelectionKey.OP_ACCEPT );
    System.out.println( "Listening on port "+port );
    int n = 0;
    while (true) {
    // See if we've had any activity -- either
    // an incoming connection, or incoming data on an
    // existing connection
    int num = selector.select();
    // If we don't have any activity, loop around and wait
    // again
    if (num == 0) {
    continue;
    // Get the keys corresponding to the activity
    // that has been detected, and process them
    // one by one
    Set keys = selector.selectedKeys();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
    // Get a key representing one of bits of I/O
    // activity
    SelectionKey key = (SelectionKey)it.next();
    // What kind of activity is it?
    if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
    SelectionKey.OP_ACCEPT) {
    System.out.println( "accept request" );
    // It's an incoming connection.
    // Register this socket with the Selector
    // so we can listen for input on it
    SocketChannel sc = ((ServerSocketChannel)key.channel()).accept();
    System.out.println( "Got connection from "+sc.socket());
    // Make sure to make it non-blocking, so we can
    // use a selector on it.
    //SocketChannel sc = s.getChannel();
    sc.configureBlocking( false );
    // Register it with the selector, for reading
    sc.register( selector, SelectionKey.OP_READ| SelectionKey.OP_WRITE);
    } else if ((key.readyOps() & SelectionKey.OP_READ) ==
    SelectionKey.OP_READ) {
    //ssc.register(selector , SelectionKey.OP_READ);
    SocketChannel sc = null;
    try {
    // It's incoming data on a connection, so
    // process it
    sc = (SocketChannel)key.channel();
    Socket s1 = sc.socket();
    s1.setTcpNoDelay(true);
    System.out.println( "enter processing data" );
    boolean ok = processInput( key );
    synchronized (selector) {
    key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
    // If the connection is dead, then remove it
    // from the selector and close it
    if (!ok) {
    key.cancel();
    System.out.println("dead");
    Socket s = null;
    try {
    s = sc.socket();
    s.close();
    } catch( IOException ie ) {
    System.err.println( "Error closing socket "+s+": "+ie );
    } catch( IOException ie ) {
    ie.printStackTrace();
    // On exception, remove this channel from the selector
    key.cancel();
    System.err.println( "Error raised in this socket");
    try {
    sc.close();
    } catch( IOException ie2 ) { System.out.println( ie2 ); }
    System.out.println( "Closed "+sc );
    else if ((key.readyOps() & SelectionKey.OP_WRITE) ==
    SelectionKey.OP_WRITE) {
    System.out.println("Enter Writing");
    String response = new String();
    if((response=this.test.getInfo())!=null){
    resBuf.clear();
    SocketChannel sc = (SocketChannel)key.channel();
    resBuf = ByteBuffer.wrap( response.getBytes("ISO-8859-1" ) );
    sc.write( resBuf );
    synchronized (selector) {
    key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
    // We remove the selected keys, because we've dealt
    // with them.
    keys.clear();
    } catch( IOException ie ) {
    System.err.println( ie );
    private boolean processInput( SelectionKey key ) throws IOException {
    buffer.clear();
    SocketChannel sc = (SocketChannel)key.channel();
    sc.read( buffer );
    buffer.flip();
    String response = new String("response ok");
    // If no data, close the connection
    if (buffer.limit()==0) {
    return false;
    Charset charset=Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);
    System.out.println(charBuffer.toString());
    System.out.println( "Processed "+buffer.limit()+" from "+sc );
    return true;
    static public void main( String args[] ) throws Exception {
    int port = Integer.parseInt( args[0] );
    System.out.println(port);
    new Server( port );
    cilent:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Client implements Runnable
    private String host;
    private int port;
    private int acport;
    //the size of buffer on how much we write and read per cycle
    private static final int maxWriteSize = 128;
    public Client( String host, int port, int numThreads ) {
    this.host = host;
    this.port = port;
    for(int i =0;i<50;i++){//initialize 50 client threads
    new Thread(this).start();
    public void run() {
    byte buffer[] = new byte[maxWriteSize];
    byte buffer2[] = new byte[maxWriteSize];
    try {
    Socket s = new Socket( );
    InetSocketAddress sa = new InetSocketAddress(host,this.port);
    s.connect(sa);
    System.out.println(s);
    s.setTcpNoDelay(true);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    for (int i=0; i<maxWriteSize; ++i) {
    buffer[i] = (byte)'a';
    out.write( buffer, 0, maxWriteSize );
    int pause = 500;
    in.read( buffer , 0 , maxWriteSize );
    System.out.println( Thread.currentThread()+" wrote "+maxWriteSize);
    String res = new String ( buffer );
    String res2 = new String ( buffer2 );
    System.out.println( res );
    try { Thread.sleep( pause ); } catch( InterruptedException ie ) {}
    } catch( Exception ie ) {
    ie.printStackTrace();
    System.err.println(ie.getMessage());
    static public void main( String args[] ) throws Exception {
    String host = "127.0.0.1";
    int port = Integer.parseInt( args[0] );
    int numThreads = Integer.parseInt( args[1] );
    new Client( host, port, numThreads );

    I have found the reason!!!
    because of system resource limitation,windows can't afford to maintain
    so many concurrent stream-IO,so some socket will be closed.
    I modified the client side code,adding thes segments to client instantialize
    such as :
    public Client( String host, int port, int numThreads ) {
    for(int i =0;i<1000;i++){
    new Thread(this).start();
    try {
    Thread.currentThread().sleep(100);//give system some idle
    } catch (InterruptedException e) {
    /* ignore */
    then the server can accept more than 1000 client request concurrently.

  • NIO non-blocking i/o- Any advantages for UDP server??

    Hi,
    I am developing a classic UDP-based server which serves hundreds of clients simultaneously. After receiving a simple request from a client, the server replies with a simple response (messages are no larger than 50 bytes).
    What, if any non-blocking-related advantages would there be in using nio? Specifically, if I used select() without turning on non-blocking on the data channel, what do I lose?
    The architecture consists of only one socket for responding to client requests. It uses receive() and send(), not read()/write()/connect().
    Thanks in advance,
    Dan.

    >>
    What, if any non-blocking-related advantageswould
    there be in using nio? Specifically, if I used
    select() without turning on non-blocking on thedata
    channel, what do I lose?You cannot do this. The runtime will throw an
    IllegalBlockingModeException when you tried to
    register it.
    So in order to use select(), your registered channels must
    be in non-blocking mode? Why? That's just the way it is?
    So to conclude, using non-blocking mode provides no real advantage for
    my application. It is only required or else I would not be able to use
    select(), right? If so, what is so good about nio? Can you give an example that is similar to my application which would benefit from the non-blocking characteristic of nio?
    Thanks for your help so far...
    Daniel.
    >>
    The architecture consists of only one socket for
    responding to client requests. It uses receive()and
    send(), not read()/write()/connect().If you are only reading from one socket there are
    theoretical advantages to servicing requests on more
    than one thread, but you would not use non-blocking
    mode to do this.
    However I think some operating systems have
    performance problems when doing this. Look at this
    article under accept serialization:
    http://httpd.apache.org/docs/misc/perf-tuning.html
    The same problems may apply to multi-thread udp socket
    readers.

Maybe you are looking for

  • How do I make a user to update to the current flash player

    I was able to gather info on how to test and display users OS and FP version. However this info is "dormant" it is just being displayed on the screen. Does anyone know how to make an alert message to upgrade to the current Flash Player if a user runs

  • NPS Discarding RADIUS request from Cisco switch (802.1x)

    Last few weeks I've been busy to get the following to work: - Cisco 2960 switch as the suppliant - Another Cisco 2960 as the authenticator switch - The supplicant is only able to send MS-EAP MS-ChapV2 requests - The NPS server is Windows 2008 R2 (and

  • How to transport this Request ?

    Hi, I want to transport a Request from D10 (100) to Q10 (230), so i release it in D10 with a Tcode : SE10 but when i diplay a list of Requests in Q10 with a Tcode STMS i don't find my Request to import it !!!! Please how to solve that? Regards.

  • Amazon Website - Where's the top of the page?

    I am using Safari, and when I go to Amazon, the Amazon heading and search box that used to appear is gone. I have no idea what happened, but could someone tell me if there is a setting in Mac OS to fix this? Thanks.

  • Best way to save

    I have filled a 500 GB external harddrive with iMovie and iDVD files. I know I can archive them in iDVD and dump both files but when I tried too do this with one movie, the archive was bigger than both files combined. I tried saving as disk image whi