NIO SocketChannel truncating write from MappedByteBuffer

Hello!
I'm running SDK build 1.4.1_01-b01 on Win2K (SP3), but I can also duplicate this on Linux (2.4 kernel).
I'm writing a simple file server, and it uses the following code:FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
sc.write(buffer);
sc.close()However applications that download (not just Java applications) do not receive the entire file. The server reports sending all of the bytes (sc.write() returns the value from fc.size()) but it is not all received byt the client downloading (I'm using wget on a Linux box).
NIO has no way to flush, so... ok this is where I'm lost. Am I doing this all wrong?
I even triedsc.socket().getOutputStream().flush();to no avail.
Another similar example of this problem is the code from this article at JavaWorld:
http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html
The zip file contains only one class file that runs, except serving up say a 300kB Jar file does not work.

Firstly thankyou very much for your time so far...
I hope I'm not tripping over the protocol, I have implemented a simple HTTP server.
The important section of code (very cut down - no log messages and less Exception handling) is:public class HttpGetHandler extends Thread {
    private SocketChannel sc;
    private File file;
    public HttpGetHandler_1(SocketChannel pSocketChannel, File pFile) {
        super("HttpGetHandler");
        this.sc = pSocketChannel;
        this.file = pFile;
        start();
    public void run() {
        try {
            // Open the file and then get a channel from the stream
            FileInputStream fis = new FileInputStream(file);
            FileChannel fc = fis.getChannel();
            // Get the file's size and then map it into memory
            long sz = (int) fc.size();
            // Create Header
            String header = new String(
            "HTTP/1.0 200 OK\r\n"
            + "Content-Length: " + sz + "\r\n"
            transmitBuffer(ByteBuffer.wrap(header.getBytes()));
            long position = 0;
            while (position < sz) {
                MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, position, sz - position);
                transmitBuffer(buffer);
                position += buffer.capacity();
        } catch (Exception e) {
        } finally {
            try {
                // HACK
                try {
                    Thread.currentThread().sleep(20000);
                } catch (InterruptedException e) {
                    log.warn("InterruptedException", e);
                sc.close();
            } catch (IOException e) {
    private void transmitBuffer(ByteBuffer pBuffer) throws IOException {
        while (pBuffer.hasRemaining()) {
            sc.write(pBuffer);
}

Similar Messages

  • Request & Response in NIO SocketChannel

    Hi
    I just reading NIO, SocketChannel.
    Here I found short tutorial with examples:
    http://developer.java.sun.com/developer/technicalArticles/releases/nio/
    in ReadURL.java says about send some request
    <Socket Channels>
    String request = "GET / \r\n\r\n";
    channel.write(encoder.encode(CharBuffer.wrap(request)));
    Q?: What is response to this request and how generate this request?
    <Non-Blocking Servers>
    in Server.java is sending back a canned text message for each request
    Q?: How I can read request that send client (ReadURL) then hence send response?
    any suggestions or other tutorial links,
    Thanks,
    ~Hill

    http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html

  • Can't read or write from iPod when it syncs with a big library

    When I try to sync with my 50Gb size library in the iTunes installed on my iBook G4 (10.4.11), it appears "can't read or write from the ipod", in the middle of the synchronization. It starts to do the job very well, but when it has done only 6 or 8 Gb, the process got slower until it appears such message. I have iTunes 7.6 and ipod firmware 1.1. I have tried on Windows and Mac plattforms, trying all the combinations (Mac and/or Win formats) and the trouble persists. The device has only two weeks of use, and it was working perfectly until now. The problem it is the same if I do it manually (no automatic sync). I am not sure if the problem is defective hardware, does anybody have any idea or have similar problem? Thanks.

    Thanks a lot for your answer. The idea of an increasing autoplaylist it is pretty good. I did it, in 5 Gb steps, and in the thrid step (10 Gb done), when it only has copied almost one Gb, the error message pop up again. Before the message appears, iTunes become slower and slower copyng each song until it stops in one song, and after a while, message appears. After, the system come down, almost blocked, and it takes a long until I can mount the ipod again. Of course, ipod restarts automatically and the songs copied in the last step are not there. I was taking care in every moment of the process, avoiding to leave the system suspend alone (and also turning off all the saving energy options). I am now pretty sure that the problem is on the device. Anyway, thank you very much for your valuable ideas.

  • Can i write from a URLConnection ?

    Can i write from a URLConnection ?
    I can read but can i write on a txt file ?

    You can upload, just as you would upload from an HTML page with a form and a Submit button. That's what you can do.

  • Read and write from access

    I am arun, a beginner in the field of LabVIEW. Now I am trying to read and write data from MS Access with out database connection toolset. How this possible. How I can use activex in Labview for doing this. Please give me some reference materials.

    Hi Arun,
    The following discussion forum talks about the same issue, and provides a good explanation and references for the different options. Also, which version of LabVIEW are you using?
    How to read/write from Access database
    Thanks,
    Lesley Y.

  • Write from SEM BPS in a infoobject in BW

    Hi there,
    does anyone know how to write from SEM BPS into an infObject in BW?
    Many thanks and regards,
    Antonino

    Hi David,
    integrating BPS Web Interface with a custom BSP application works fine. There's one thing that you have to remember, however. BPS buffers master data access. So if you change the attribute of existing master data entries, those changes will not be active until you exit the BPS Web Interface and restart it.
    Regards
    Marc
    SAP NetWeaver RIG

  • Read/write from OBIEE repository data using API

    Hi, I need to create a my own application that could read/write from the repository data, the same as I can do using the BI Admin user interface (like creating dimensions, hierarchies, levels, etc.).
    Are there any API's to do that?
    I'm usually working with .NET/C# technology but I can also programming in Java, the important is that I could be able to write metadata in the repository, and simply read them, I'm not interested in complex report functions... any suggestion will be appreciated!

    I've looked for it before, but I didn't find anything about BI Server accessing, so I requested on this forum. After that I've looked for another kind of API and I've found these about web services!
    In the PDF I linked says:
    "Oracle BI Web Services allows external applications such as J2EE and .NET to use Oracle Business
    Intelligence as an analytical calculation and data integration engine. It provides a set of Presentation
    Services that allow external applications to communicate with Oracle BI Presentation Services. You
    can use Oracle BI Web Services to extract results from Oracle BI Presentation Services and deliver
    them to external applications and Web application environments. You can reference a saved report
    or send the criteria for the report to Oracle BI Web Services."
    without talking about Metadata, but in this another tutorial http://oraclebizint.wordpress.com/2007/07/31/customizing-obi-ee-soap-api/ talks about "metadata"... is it only about Presentation Service? Has Presentation Service metadata too? Are they like Dimensions and hierarchies?
    Excuse me but although I've read the documentation I can't understand what kind of metadata it refers to...

  • How to write from database to XML file using JAVA and back..

    Hi....
    I am strugling for a code to write from database to xml output instead of what i have written in flat file....could anyone please help me out...to do this and again read the same back to the database using java...

    Hi,
    In java world, there is a tutorial on what you are looking for :
    http://www.javaworld.com/javaworld/jw-01-2000/jw-01-dbxml_p.html
    It uses SAX/DOM parsers to translate XML data into the appropriate fields of the database and visa-versa.
    Hope it helps.

  • Read/Write from an Applet

    hi,
    I need to read/write from/to a file from an Applet. Reading is no Problem. Actually writing is!
    I have try it but I get some problems with the getOutputStream function.
    Can everybody send me an simple example.

    You are right and I have try it.
    There are some guys with the same problem but there are no answers to the specified problem.

  • Reading from java.nio.SocketChannel

    Hi guys,
    can anyone tell me how can i read from a SocketChannel a certain number of bytes instead reading whole buffer.
    The only method that i find is to have multiple ByteBuffer and allocate them the number of bytes that i want to read.
    Ex.
    An client send me 20 bytes.
    I want to read 1 first , 9 second and last the rest.
    i do something like that :
    ByteBuffer b1 = ByteBuffer.allocate(1);
    ByteBuffer b2 = ByteBuffer.allocate(9);
    ByteBuffer b3 = ByteBuffer.allocate(10);and then read in eatch buffer.
    Is there another way to read using only one buffer .
    Thank's
    Danny

    The main idea behind buffers is max reuse of objects (therefore minimal calls to the Garbage Collector). You should only need one for reading.
    When reading from a SocketChannel, it just fills up whatever buffer you give it as full as it can. (Could be one byte, could be a million, doesn't matter, don't be concerned) Then, you can just flip the buffer, read the data to wherever, reset it and it's good to go again. If you find yourself concerned with how many bytes you've read (unless you want to explicitly keep track for some reason like display purposes), you are immediately on the wrong path, as the SocketChannel/Buffer combination will take care of this for you.

  • Java NIO - copy-on-write buffer

    This is regarding peculiar behavior of a Java program on Linux-IA64 platform.
    I have a Java program that uses MappedByteBuffer. For the same file, there are three buffers - read only, read/write and copy-on-write (cow)
    First, change contents of cow buffer and print all buffers. The change is reflected only in cow buffer (not in ro or rw) - as expected.
    Then, change contents of r/w buffer and print all buffers. The change is NOT observed in cow buffer, but reflected in ro and rw buffers (for Linux-IA64). I tried the same program in Linux-X86 and the change is reflected in all buffers (including cow buffer).
    I used JDK 1.4.2_03 for compiling and running. The doc for MappedByteBuffer says
    "The content of a mapped byte buffer can change at any time, for example if the content of the corresponding region of the mapped file is changed by this program or another. Whether or not such changes occur, and when they occur, is operating-system dependent and therefore unspecified."
    Is this behaviour acceptable? Is this observed in any other platform?
    I think Java NIO leaves it to the O/S and JVM is not doing anything here (as different from java.io). This could probably result in inconsistent behaviour across platforms (though it improves performance)
    Please let me know your thoughts.

    My thought is that you have posted this to the wrong forum.

  • NIO problem: multiple write

    Hello.
    I am using a NIO server for my application with a pool of WorkingThreads to handle client requests.
    The read part seems to work fine (I am deregistering the OP_READ interest when I begin to read from the socketchannel and I register it back when I finish processing the data). This way I am able to process data coming in chunks down the stream.
    Now, the problem I have is with writing data back to the client. If I send the data with only 1 socketChannel.write(ByteBuffer) method the client gets it correctly. But if I try to write in a while() loop more messages it happens that the client receives the first chunk correctly but SOMETIMES it receives rubbish as the next chunks. My guess is that after the first write(), the server may send some zeros to the client just before the next chunk so the client interprets that as valid data.
    I have tried to unregister the key from writing (key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE))) immediatelly after I've done a write() and reregister it for writing just before I want to send the data but this didn't help. I'm sure this is solvable but I haven't met anywhere code that deals with writing more than 1 buffer (like writing a big file for example).
    Any help would be very much appreciated.
    Thank you.
    Bogdan

    Thank you for replying, ejp, but it seems that what you said is not quite true. Here is my send method:
    public void send(SelectionKey key) {
         try {
              if (sendMessages.size() != 0) {
                   String message = null;
                   while (sendMessages.size() > 0) {
                        synchronized (sendMessages) {
                             message = (String) sendMessages.removeFirst();
                        ByteBuffer theBuffer = ByteBuffer.wrap(message.getBytes());
                        theBuffer.put(message.getBytes());
                        theBuffer.flip();
                        ((SocketChannel) key.channel()).write(theBuffer);
                        theBuffer.flip();
                        log.debug("Sent message:" + decoder.decode(theBuffer));
              key.interestOps(key.interestOps() | SelectionKey.OP_READ);
              key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
         } catch (IOException e) {
              key.cancel();
    }I verify what I send by outputting with the line log.debug("Sent message:" + decoder.decode(theBuffer));The messages are strings which are being taken from a LinkedList. The chunks I'm sending are of size 4096 bytes.
    I forgot to mention that the client uses simple IO (blocking mode). In between the sendings from the server it receives zeros and considers them as part of the message.
    I am using Windows 2000 + JDK 1.4.2_01

  • NIO SocketChannel Re-Connection problem

    Hello all,
    I am developing poker game. in that i am using socketchannel. if any client have some problem and if it disconnects i have to reconnect the client and i have to establish a new connection. means i have to create another socketchannel. means again sends request, accept , read, write all that, and that is decresing the performance of the server.
    Is there any way to ramain socketchannel open. if it disconnects then reconnect it?
    Waiting for reply...............
    Hitesh Shekhada

    Wilson, execute <?php phpinfo(); ?> in the web server and see whether you see the proper ORACLE_HOME. Here is how to do it from CLI if
    you are on some version of Unix:
    [mgogala@dibidus ~]$ php -r 'phpinfo();'|grep ORACLE|grep SERVER
    SERVER["ORACLESID"] => test11
    _SERVER["ORACLE_BASE"] => /oracle
    _SERVER["ORACLE_HOME"] => /oracle/product/11.1.0
    [mgogala@dibidus ~]$
    If your environment is set properly (ORACLE_HOME is visible), OCI8 driver will look into $TNS_ADMIN/sqlnet.ora to see what method for the
    name resolution should be used. The default for the TNS_ADMIN is $ORACLE_HOME/network/admin. If the sqlnet.ora file says that
    the default method is "tnsnames", OCI8 will inspect the tnsnames.ora file to resolve the DB name. You will have to check the syntax
    of that file, too.

  • NIO SocketChannel non-blocking read

    Hello.
    I'm not sure a resembling message has already been posted in a forum. In such a case, thanks for redirecting to it.
    Goals :
    A selector is used by a main server thread to make accept and read operations non-blocking.
    When a connection is accepted, the newly created socket channel is configured as non-blocking, and a key is added to the selector with the OP_READ flag.
    When data are available on sockets, a new task (runnable) is created and submitted to a thread pool.
    When a thread is ready to process the request, a pre-allocated bytebuffer is used to read arriving data.
    The problem :
    When the bytebuffer capacity is less than the received bytes count, the read method on the socket channel interrupts the selector on the same selection key. In response to this event, a new task is initiated, interferring with the previous one.
    As expected according to my concurrency policy (ie. with a pool of threads), several requests are processed by parallel threads. To avoid unsafe accesses, i added a synchronized statement on the channel blocking lock, and it seems to works fine. But a better way should exist...
    Questions :
    Is this the expected behavior ?
    Is there any other way to read received data with a small buffer ?
    The full copy of the source code :
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.nio.charset.*;
    import java.net.*;
    import java.util.*;
    import net.moon.threads.*;
    public class Nio1 {
         static class Request {
              boolean isCompleted = false;
              int inputs = 0;
              Set workers = new HashSet();
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              byte p = 0;
              boolean isCompleted() {
                   return isCompleted;
              void countInput() {
                   inputs++;
              void append(final ByteBuffer byteBuffer) {
                   if (isCompleted)
                        throw new IllegalStateException("Request is already completed");
                   workers.add(Thread.currentThread());
                   while (byteBuffer.hasRemaining()) {
                        byte b = byteBuffer.get();
                        baos.write(b);
                        if ((b == '\r') && (p == '\n'))
                             isCompleted = true;
                        p = b;
              int inputs() {
                   return inputs;
              Thread[] workers() {
                   return (Thread[]) workers.toArray(new Thread[0]);
              int size() {
                   return baos.size();
              byte[] getData() {
                   return baos.toByteArray();
              void reset() {
                   isCompleted = false;
                   inputs = 0;
                   baos.reset();
                   workers.clear();
         static private class RequestTask implements Runnable {
         private final static Charset charset = Charset.forName("US-ASCII");
              private final Server server;
              private final SelectionKey selectionKey;
              RequestTask(final Server server, final SelectionKey selectionKey) {
                   this.server = server;
                   this.selectionKey = selectionKey;
              public void run() {
                   log("*** Processing input...");
                   try {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
    synchronized(channel.blockingLock()) {
                        Request request = (Request) selectionKey.attachment();
                        request.countInput();
                        State state = getState();
                        log("Reading first...");
                        int c = channel.read(state.byteBuffer);
                        log("... Read first : " + c);
                        if (c > 0) {
                             for(;;) {
                                  state.byteBuffer.flip();
                             request.append(state.byteBuffer);
                                  state.byteBuffer.clear();
                                  if (c < state.byteBuffer.capacity()) break;
                                  log("Reading next...");
                                  c = channel.read(state.byteBuffer);
                                  log("... Read next : " + c);
                                  if (c <= 0) break;
                             if (request.isCompleted()) {
                                  log("Request completed : " + request.inputs());
                                  StringBuffer bodyBuffer = new StringBuffer();
                                  bodyBuffer.append("-----------------------------\r\n");
                                  bodyBuffer.append("Request processed in " + request.inputs() + " inputs\r\n");
                                  bodyBuffer.append("Request size is " + request.size() + " bytes\r\n");
                                  bodyBuffer.append("Participating workers :\r\n");
                                  Thread[] workers = request.workers();
                                  for (int i = 0; i < workers.length; i++)
                                       bodyBuffer.append(" * " + workers[i] + "\r\n");
                                  bodyBuffer.append("-----------------------------\r\n");
                                  StringBuffer headerBuffer = new StringBuffer();
                                  headerBuffer.append("HTTP/1.1 200 OK\r\n");
                                  headerBuffer.append("Server: NIO Server 1\r\n");
                                  headerBuffer.append("Content-Type: text/plain\r\n");
                                  headerBuffer.append("Content-Length: ").append(request.size() + bodyBuffer.length()).append("\r\n");
                                  headerBuffer.append("\r\n");
                             CharsetEncoder encoder = charset.newEncoder();
                                  channel.write(encoder.encode(CharBuffer.wrap(headerBuffer)));
                                  channel.write(encoder.encode(CharBuffer.wrap(bodyBuffer)));
                                  channel.write(ByteBuffer.wrap(request.getData()));
                                  request.reset();
                        if (c < 0) {
                             selectionKey.attach(null);
                             selectionKey.cancel();
                             log("!!! Connection terminated for channel " + channel);
                   catch(final Exception x) {
                        x.printStackTrace();
                   log("*** Request processed...");
              private State getState() {
                   State state = (State) server.taskManager.getCurrentWorkerState();
                   if (state == null) {
                        state = new State();
                        server.taskManager.setCurrentWorkerState(state);
                   else {
                        state.byteBuffer.clear();
                   return state;
              private void log(final String text) {
                   System.out.println(Thread.currentThread() + " : " + text);
              static class State {
                   ByteBuffer byteBuffer = ByteBuffer.allocateDirect(32);
         static private class Server implements Runnable {
              private final int port;
              private Thread worker;
              private FIFOTaskManager taskManager;
              Server(final int port) {
                   this.port = port;
                   worker = null;
              synchronized void start() throws Exception {
                   if (worker == null) {
                        log("Starting the server...");
                        taskManager = new FIFOTaskManager("Nio1Workers", 24);
                        worker = new Thread(this);
                        worker.start();
                        synchronized(worker) {
                             try {
                                  worker.wait();
                             catch(InterruptedException x) {
                        log("Server started !");
              public void run() {
                   try {
                        log("Server is starting...");
                        Selector selector = SelectorProvider.provider().openSelector();
                        log("Creating listener on port " + port);
                        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                        serverSocketChannel.configureBlocking(false);
                        InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
                        serverSocketChannel.socket().bind(inetSocketAddress);
                        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                        synchronized(worker) {
                             worker.notify();
                        while (selector.select() >= 0) {
                             Set readyKeys = selector.selectedKeys();
                             log("Keys are ready : " + readyKeys.size());
                             for (Iterator i = readyKeys.iterator(); i.hasNext(); ) {
                                  SelectionKey selectedKey = (SelectionKey) i.next();
                                  if (selectedKey.isAcceptable()) {
                                       ServerSocketChannel ssc = (ServerSocketChannel) selectedKey.channel();
                                       SocketChannel sc = ssc.accept();
                                       sc.configureBlocking(false);
                                       SelectionKey sk = sc.register(selector, SelectionKey.OP_READ);
                                       sk.attach(new Request());
                                       log("Connection accepted for channel " + sc);
                                  else if (selectedKey.isReadable()) {
                                       log("Key ready for input : " + selectedKey);
                                       taskManager.execute(new RequestTask(this, selectedKey));
                                  i.remove();
                             readyKeys = null;
                        log("Server loop interrupted !");
                   catch(Exception x) {
                        x.printStackTrace();
              private void log(final String text) {
                   System.out.println("SERVER: " + text);
         public static void main(final String[] args) throws Exception {
              Server server = new Server(9001);
              server.start();

    Thanks for the trick. I hope the code will be more readable than my sockets !
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.nio.charset.*;
    import java.net.*;
    import java.util.*;
    import net.moon.threads.*;
    public class Nio1 {
         static class Request {
              boolean isCompleted = false;
              int inputs = 0;
              Set workers = new HashSet();
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              byte p = 0;
              boolean isCompleted() {
                   return isCompleted;
              void countInput() {
                   inputs++;
              void append(final ByteBuffer byteBuffer) {
                   if (isCompleted)
                        throw new IllegalStateException("Request is already completed");
                   workers.add(Thread.currentThread());
                   while (byteBuffer.hasRemaining()) {
                        byte b = byteBuffer.get();
                        baos.write(b);
                        if ((b == '\r') && (p == '\n'))
                             isCompleted = true;
                        p = b;
              int inputs() {
                   return inputs;
              Thread[] workers() {
                   return (Thread[]) workers.toArray(new Thread[0]);
              int size() {
                   return baos.size();
              byte[] getData() {
                   return baos.toByteArray();
              void reset() {
                   isCompleted = false;
                   inputs = 0;
                   baos.reset();
                   workers.clear();
         static private class RequestTask implements Runnable {
             private final static Charset charset = Charset.forName("US-ASCII");
              private final Server server;
              private final SelectionKey selectionKey;
              RequestTask(final Server server, final SelectionKey selectionKey) {
                   this.server = server;
                   this.selectionKey = selectionKey;
              public void run() {
                   log("*** Processing input...");
                   try {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
    synchronized(channel.blockingLock()) {
                        Request request = (Request) selectionKey.attachment();
                        request.countInput();
                        State state = getState();
                        log("Reading first...");
                        int c = channel.read(state.byteBuffer);
                        log("... Read first : " + c);
                        if (c > 0) {
                             for(;;) {
                                  state.byteBuffer.flip();
                                 request.append(state.byteBuffer);
                                  state.byteBuffer.clear();
                                  if (c < state.byteBuffer.capacity()) break;
                                  log("Reading next...");
                                  c = channel.read(state.byteBuffer);
                                  log("... Read next : " + c);
                                  if (c <= 0) break;
                             if (request.isCompleted()) {
                                  log("Request completed : " + request.inputs());
                                  StringBuffer bodyBuffer = new StringBuffer();
                                  bodyBuffer.append("-----------------------------\r\n");
                                  bodyBuffer.append("Request processed in " + request.inputs() + " inputs\r\n");
                                  bodyBuffer.append("Request size is " + request.size() + " bytes\r\n");
                                  bodyBuffer.append("Participating workers :\r\n");
                                  Thread[] workers = request.workers();
                                  for (int i = 0; i < workers.length; i++)
                                       bodyBuffer.append(" * " + workers[i] + "\r\n");
                                  bodyBuffer.append("-----------------------------\r\n");
                                  StringBuffer headerBuffer = new StringBuffer();
                                  headerBuffer.append("HTTP/1.1 200 OK\r\n");
                                  headerBuffer.append("Server: NIO Server 1\r\n");
                                  headerBuffer.append("Content-Type: text/plain\r\n");
                                  headerBuffer.append("Content-Length: ").append(request.size() + bodyBuffer.length()).append("\r\n");
                                  headerBuffer.append("\r\n");
                                 CharsetEncoder encoder = charset.newEncoder();
                                  channel.write(encoder.encode(CharBuffer.wrap(headerBuffer)));
                                  channel.write(encoder.encode(CharBuffer.wrap(bodyBuffer)));
                                  channel.write(ByteBuffer.wrap(request.getData()));
                                  request.reset();
                        if (c < 0) {
                             selectionKey.attach(null);
                             selectionKey.cancel();
                             log("!!! Connection terminated for channel " + channel);
                   catch(final Exception x) {
                        x.printStackTrace();
                   log("*** Request processed...");
              private State getState() {
                   State state = (State) server.taskManager.getCurrentWorkerState();
                   if (state == null) {
                        state = new State();
                        server.taskManager.setCurrentWorkerState(state);
                   else {
                        state.byteBuffer.clear();
                   return state;
              private void log(final String text) {
                   System.out.println(Thread.currentThread() + " : " + text);
              static class State {
                   ByteBuffer byteBuffer = ByteBuffer.allocateDirect(32);
         static private class Server implements Runnable {
              private final int port;
              private Thread worker;
              private FIFOTaskManager taskManager;
              Server(final int port) {
                   this.port = port;
                   worker = null;
              synchronized void start() throws Exception {
                   if (worker == null) {
                        log("Starting the server...");
                        taskManager = new FIFOTaskManager("Nio1Workers", 24);
                        worker = new Thread(this);
                        worker.start();
                        synchronized(worker) {
                             try {
                                  worker.wait();
                             catch(InterruptedException x) {
                        log("Server started !");
              public void run() {
                   try {
                        log("Server is starting...");
                        Selector selector = SelectorProvider.provider().openSelector();
                        log("Creating listener on port " + port);
                        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                        serverSocketChannel.configureBlocking(false);
                        InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
                        serverSocketChannel.socket().bind(inetSocketAddress);
                        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                        synchronized(worker) {
                             worker.notify();
                        while (selector.select() >= 0) {
                             Set readyKeys = selector.selectedKeys();
                             log("Keys are ready : " + readyKeys.size());
                             for (Iterator i = readyKeys.iterator(); i.hasNext(); ) {
                                  SelectionKey selectedKey = (SelectionKey) i.next();
                                  if (selectedKey.isAcceptable()) {
                                       ServerSocketChannel ssc = (ServerSocketChannel) selectedKey.channel();
                                       SocketChannel sc = ssc.accept();
                                       sc.configureBlocking(false);
                                       SelectionKey sk = sc.register(selector, SelectionKey.OP_READ);
                                       sk.attach(new Request());
                                       log("Connection accepted for channel " + sc);
                                  else if (selectedKey.isReadable()) {
                                       log("Key ready for input : " + selectedKey);
                                       taskManager.execute(new RequestTask(this, selectedKey));
                                  i.remove();
                             readyKeys = null;
                        log("Server loop interrupted !");
                   catch(Exception x) {
                        x.printStackTrace();
              private void log(final String text) {
                   System.out.println("SERVER: " + text);
         public static void main(final String[] args) throws Exception {
              Server server = new Server(9001);
              server.start();
    }

  • Regarding NIO SocketChannel and SelectorKey

    Basics: I have a SocketChannel which is supposed to read and write.
    Context: My query is regarding the SelectoinKey for this channel. I understand that While I am writing onto this channel I would set the Key to OP_WRITE and soon after the write function is completed I should reset the SelectionKey to OP_READ
    Querry: amid the write operation, if there is some data coming from the remote entity onto the same channel then the SelectionKey being in OP_WRITE mode will I lose the incoming data?
    thanks in advance
    Amit

    While I am writing onto this channel I would set the
    Key to OP_WRITE and soon after the write function is
    completed I should reset the SelectionKey to OP_READNo. When you have data to write and you can't write it (i.e. you get a return value of zero from the channel.write() call) you should set the key to OP_WRITE, and when this event fires in the Selector (key.isWritable()) retry the write. When it succeeds completely, you then set the key back to OP_READ.
    Query: amid the write operation, if there is
    some data coming from the remote entity onto the same
    channel then the SelectionKey being in OP_WRITE mode
    will I lose the incoming data?No.

Maybe you are looking for

  • Problem in invoking Decision Service

    Hi, I am working on demo project and trying to follow SOAOrderBooking example. Problem occurs when executing DecisionServicePL (PartnerLink) in BPEL process.Please see the exception stack thanks in advance. Zain Faulted while invoking operation "asse

  • CSS reference chart for spark?

    I'm running into many issues when trying to add CSS into my project due to the way spark skins now work with CSS. Is there a CSS reference chart I can use or spark?  Also why did Adobe remove the CSS design view in flash builder 4?

  • What verson of java do I need to download for Mac OS X 10.5.8?

    What version of Java do I need to download for Mac OS 10.5.8?

  • How to discover private field using reflect?

    Hi, all: i learned discover fields of a class by using reflect getClass().getFields() but it only works for public fields. how to discover all fields of a class? thank you in advance. kevin.

  • Calling function from inside function using powershell

    In my powershell script, I am using following code, first time it will go in another function and returns back original function, but in next time in loop, it open popup "Process [0]" and asking for input. I want my second function runs for each site