Non blocking worker servlet ?

Hi friends,
I have an issue to implement. We implemented a web application and now I want to separate some parts of this application. I can express the action shorter and simple below.
if a user requests x-y ticket {
���try {
������check db if x-y is available
������if true send available
������else not
���}catch (NonExistentData) {
������addJob2Queue(x-y)
������send available
���}
class AvailabilityHelper extends Thread{
���run(){
������while(true){
���������checkQueue
���������if there is job, updateDBfor(org,dest)
������}
���}
* updateDBfor(org,dest) includes other ejb references to request data and insert it into db
This web aplication runs with JSP 1.2 EL support on WAS 5.1
the check for db and the thread implementation was in a seperate package and were used in actions of web application. Now they also want to use these checks for other (non web) applications. So i think there should be a session bean in ejb and should process these requests and I used JMS (Message-Driven Bean) with WebSphere MQ to undertake the thread and queue mechanism.
Now it works like this :
class exampleSessionBean{
���getAvalibability(org, dest){
������try {
���������check db if x-y is available
���������if true send available
���������else not
������}catch (NonExistentData) {
���������queueSender.sendMessage(update x-y)
���������send available;
������}
���}
class queueMDB{
���onMessage(){
������updateDBfor(org,dest)
���}
The purpose of this applications was, not to block the user for db update process, if there is data in db select and show to the user. the update process of db includes other ejb references and takes so much time. It is nonsense to make the user wait such time. And the info is not a big deal, because of this when i put a request for update, without blocking i send it as available...
So what is the problem ? :) Deployment team don't want to pay for websphere MQ and hire a admin for that. Also they don't want to use Embedded Messaging server client (JMS Server) of WAS. So I am asking you: is there a way to implement a non blocking servlet so that i will just make a request and don't wait for response, or a servlet will take the request and release the connection but will continue to process the request ?
thanks for all...

I tried to implement a web application and add a ServletContextListener as stevejluke suggests. But on contextInitialized function when creating new JobConsumer it gets following errors on server.
6/27/06 12:51:36:391 CEST] 33238138 WebContainer A SRVE0169I: Loading Web Module: non-blocking.
[6/27/06 12:51:36:438 CEST] 33238138 SystemOut O OlaListener initializing...
[6/27/06 12:51:36:516 CEST] 33238138 SystemOut O OlaListener - Queue added
[6/27/06 12:51:36:516 CEST] 33238138 SystemOut O OlaListener - keepWorking
[6/27/06 12:51:36:672 CEST] 33238138 WebApp E SRVE0015E: Failure to initialize Web application non-blocking
[6/27/06 12:51:36:844 CEST] 33238138 WebGroup E SRVE0054E: An error occurred while loading Web application
public class OlaListener implements ServletContextListener {
     * @see javax.servlet.ServletContextListener#void (javax.servlet.ServletContextEvent)
     public void contextDestroyed(ServletContextEvent event) {
             ServletContext context = event.getServletContext();
             context.setAttribute("keepWorking", Boolean.FALSE);
     * @see javax.servlet.ServletContextListener#void (javax.servlet.ServletContextEvent)
     public void contextInitialized(ServletContextEvent event) {
             System.out.println("OlaListener initializing...");
             ServletContext context = event.getServletContext();
             WorkQueue newJobs = new WorkQueue();
             context.setAttribute("newJobs", newJobs);
             System.out.println("OlaListener - Queue added");
             context.setAttribute("keepWorking", Boolean.TRUE);
             System.out.println("OlaListener - keepWorking");
             JobConsumer jc = new JobConsumer();
             System.out.println("OlaListener - Job Consumer created");
             jc.setContext(context);
             System.out.println("OlaListener - context set");
             Thread t = new Thread(jc);
             t.start();
public class JobConsumer implements Runnable{
     /*log4j*/     private static final Logger logger = Logger.getLogger(JobConsumer.class);     
     private ServletContext context = null;
     public void run(){
             System.out.println("JobConsumer - run Start");
             processQueue(context);
             System.out.println("JobConsumer - run End");
}

Similar Messages

  • Non-blocking J2EE calls

    We wish to connect fat clients (in our case Powerbuilder) to a J2EE environment (Weblogic). We also need to make some of the calls from the fat client non-blocking (asynchronous). With many clients, JMS was rejected as a mechanism.
    Our first solution, which works as a prototype, was to package a Java bean as an OLE object and deploy it to the client. This bean could make the calls non-blocking. However there are registry issues (the packaging implies a pre-defined directory structure), we need a JRE on every client and 15Mb of weblogic jars (aaargh), so it only really works as a prototype.
    The next (current) solution is a C dll that can be called from Powerbuilder and uses a socket to talk to a Java J2EE Gateway on the server. This Gateway makes the system non-blocking and calls the EJBs. This is clearly easier in terms of configuring the client.
    Ideally we would like to drop the Gateway by finding a non-blocking way to get into J2EE from the C dll but the only methods we have thought of:
    - simulating an HTTP servlet call
    - SOAP
    are synchronous (or appear to be, my knowledge of SOAP is limited).
    Has anyone come across other ways of getting non-blocking communications with J2EE?

    CORBA, this is what it was designed to do, but it is not not a light weight solution.

  • Non-blocking file access?

    1. Did I miss something: is there a way in java 1.5 (or even java 1.6) to read files and query file metadata (size, last modified, that kind of thing) in a non-blocking manner?
    2. Is there a way to figure out where physical harddrive boundaries lie without resorting to tricks like running 'df' and parsing the output, which is rather un-portable? I obviously don't want to create a thread per file read (one aim is that the maximum number of threads is constant - even with a gazillion requests the amount of threads will never exceed a (low) constant.) but just 1 thread to perform all required reads would possibly end up wasting time if there are multiple harddrives and the CPU is idling anyway. I'd guess at this point that 1 thread per physical harddrive handling all file access is the best way to go, but how do I figure out those boundaries?
    3. Is NIO2 (JSR 203) going to add features to work with files in a non-blocking way?
    4. Is there a full-stack (templating, database access, writing web services, serving up the data) web server out there someplace that works entirely on a non-blocking methodology? I don't think so, but I might have missed something. JETTY tries something, but the servlet specs fundamentally do not work with non-blocking I/O, so it doesn't count.
    background:
    I'm writing a non-blocking webserver. KISS is the attitude - so far the basic system and any services (my take on the servlet spec, as the servlet spec doesn't play nice with NIO principles) on it all run inside a single thread, no thread pool.
    So far it all works, and stress testing it with 1000 connections, 200 at the same time shows a process time of about half a millisecond per request, on a simple macbook, which is nice, because that beats apache even at serving up 404s.
    So far I have only written very simple test apps that for example do calculations and the like, nothing that you'd actually do with web apps, like, say, serving (template-powered) data from files on a harddrive.
    Because of the absolute requirement for each service NEVER to block while serving up bytes, manually working with files would be an unbelievable pain on the part of the web service developer. Hence I'm building templating and DB access into the system.
    Unfortunately, I realized, reading NIO specs, that there doesn't seem to be any way to perform file operations in a non-blocking manner (not just reading them, but getting file size and last modified timestamps as well). I'll obviously have to use a lot of caching tactics, but before I can cache, I need to read files somehow.
    The aim of this webserver is basically to survive massive spikes in traffic, be it from digg/slashdot, or from a DDOS attack, as best as possible, and where that isn't possible, to gracefully fall apart. That is, service as many requests as possible at a certain minimum bandwidth per request, prioritizing repeat visitors and site moderators, and deny the rest instantly, instead of just falling apart in shambles as happends in your usual LAMP or servlet design, not serving even 1 request right most of the time.
    Thanks a lot for everyone's time!

    ejp wrote:
    BufferedInputStream will improve the performance by a factor of several thousand because it cuts down on system calls.Well, that might be true if you're reading individual bytes with a call to read(), or making many small read( buffer ) requests. But if you call read( buffer ) with a reasonably sized buffer (BufferedInputStream uses 8192 bytes as a default buffer size), then you're going to get performance equal to or possibly better than a BufferedInputStream.

  • Application Builder: Can you create non-blocking, return-immediately functions in a dll?

    I need to include a procedure in a dll that is non-blocking, i.e. it should return immediately after the procedure has been called, and not return after its processes are completed.
    The procedure is a LabView 7.0 VI, and the dll is being created using the Application Builder. Currently the procedure completes its desired task and then returns, but I would like the function to return immediately. Thanks for your help!

    Rischaard,
    I don't know if that will work in a dll, however as an idea:
    use the vi-server functions:
    Your dll-procedure opens a OwnTreat.vi(wich will do the work) with vi-server, and run it without waiting for completion.
    First thing OwnTreat.vi should do is opening (with vi-server) a reference to itself (So your caller dll can close without stopping the OwnTreat.vi)
    Then OwnTreat.vi con do what YOU want. When finished close the self-reference
    Maybe you need a short wait or a feedback to make sure that OwnTreat has opened his own reverence before your dll stops.
    Greetings from Germany
    Henrik
    LV since v3.1
    “ground” is a convenient fantasy
    '˙˙˙˙uıɐƃɐ lɐıp puɐ °06 ǝuoɥd ɹnoʎ uɹnʇ ǝsɐǝld 'ʎɹɐuıƃɐɯı sı pǝlɐıp ǝʌɐɥ noʎ ɹǝqɯnu ǝɥʇ'

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

  • Non-blocking serialization

    Dear all,
    Does anybody know whether PI/XI supports the non-blocking serialization function?
    And in which version?
    If not, is there any work-around?
    Thanks a lot.
    best regards
    Jing

    HI
    Serialization plays an important role in distributing interdependent objects, especially when master data is being distributed.
    IDocs can be created, sent and posted in a specified order by distributing message types serially.
    Errors can then be avoided when processing inbound IDocs.
    Interdependent messages can be serially distributed in the following ways:
    Serialization by Object Type
    Serialization by Message Type
    Serialization at IDoc Level
    (not for IDocs from generated BAPI-ALE interfaces)
    Serialization at IDoc Level
    Use
    Delays in transferring IDocs may result in an IDoc containing data belonging to a specific object arriving at its destination before an "older" IDoc that contains different data belonging to the same object. Applications can use the ALE Serialization API to specify the order IDocs of the same message type are processed in and to prevent old IDocs from being posted if processing is repeated.
    ALE provides two function modules to serialize IDocs which the posting function module has to invoke:
    u2022 IDOC_SERIALIZATION_CHECK
    checks the time stamps in the serialization field of the IDoc header.
    u2022 IDOC_SERIAL_POST
    updates the serialization table.
    Check the following link:
    http://help.sap.com/saphelp_nw04s/helpdata/en/0b/2a66d6507d11d18ee90000e8366fc2/frameset.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/78/2175a751ce11d189570000e829fbbd/frameset.htm
    How to serialize IDoc XML messages fed into XI
    cheers

  • Non-Blocking SOAP-Message WITHOUT Messaging Provider?

    Hi there!
    Is there any possibility of sending a non-blocking SOAP-Message WITHOUT using a MessagingProvider?
    I�m thinking about a Service which doesn�t need to give any Feedback!
    Thanks alot!
    Eric Sommer

    I believe that JAXM does not support a non-blocking send without a messaging provider. However, the receiver can simply return an empty message and the sender can ignore the reply:
    public SOAPMessage onMessage(SOAPMessage msg) {
        // process message
        return messageFactory.createMessage();
    }In fact, the receiver may be able to return the same message it received. I've tried this and it works but I didn't dig into the JAXM spec to be sure it's legal.
    Mike

  • Non blocking IO in jdk1.2??

    hi All,
    I would like to know what all non blocking IO operations are available to me in jdk1.2.2 which I can use in URLConnection. Would really appreciate help from all you people :)
    Thanks in advance,
    Rishi

    Fluffy is correct but there are work arounds.
    There are two methods available() for InputStream and ready() for Reader
    The first one returns you an integer - if 0, then there are no bytes to read.
    The second returns a boolean - if false, there is nothing to read.
    Ironluca

  • Non-blocking SocketChannels

    I'm trying to learn how to use non-blocking socket channles, but I haven't found much info (nor luck) so far.
    To learn, I'm building a server and a client. The server accepts input from the clients and process it in only one thread. The clients should send Objects to the server, and the server process them and return the result also as an Object. For this, I'm trying to use ObjectOutputStream and ObjectInputStream.
    The problem I don't know how to solve is that the SocketChannel is in non-bolcking mode, so I can't use their input/output streams (I get a IllegalBlockingModeException). In the server process loop I can reconfigure the SocketChannel to blocking mode to be able to read the Object, but I can't configure it to non-blocking mode again because I get a CancelledKeyException.
    Does anyone know how to work with InputStreams and non-blocking channels? Or where to find more info about it?
    Here are the relevant part of the server code:
    Set ready = selector.selectedKeys();
    Iterator i = ready.iterator();
    while (i.hasNext()) {
       try {
          SelectionKey sk = i.next();
          i.remove();
          if (sk.isAcceptable()) {
             ServerSocketChannel ssc = (ServerSocketChannel)sk.channel();
             SocketChannel sc = ssc.accept();
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ);
          } else if (sk.isReadable()) {
             SocketChannel sc = (SocketChannel)sk.channel();
             // PROBLEM: If the channel is in non-blocking mode
             // I cannot use InputStreams
             sk.cancel();
             sc.configureBlocking(true);
             // Read the object sent by the client
             ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(sc));
             Object o = in.readObject();
             // PROBLEM: Can't put the channel back to non-blocking mode
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ); // CancelledKeyException
       } catch (...){
    }

    In my client, this is working fine:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    for (int i = 0; i < 30000; i++) {
       oos = new ObjectOutputStream(sc.socket().getOutputStream());
       oos.writeObject(object);
       oos.flush();
       ois = new ObjectInputStream(sc.socket().getInputStream());
       Object o = ois.readObject();
    }But trying to do it like this throws a StreamCorruptedException at the server side.
    ObjectOutputStream oos = new ObjectOutputStream(sc.socket().getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(sc.socket().getInputStream());
    for (int i = 0; i < 30000; i++) {
       oos.writeObject(object);
       oos.flush();
       Object o = ois.readObject();
    }Do you know why?

  • Non-Blocking call to read the Keyboard

    does anyone know how to make a JAVA program make a non-blocking call to read the keyboard? eg. write a program which generates prime number until a keyboard key is pressed.

    if you use a gui you can use keyListener
    Would work only if your gui elements have focus right now.

  • Using non blocking connect() call for SCTP sockets in Solaris10

    Hi,
    I have a problem with non blocking connect call on SCTP socket.
    I am using the sctp stack support in Solaris10.
    When the connect is successful, I can get the pollout event on the socket.
    But there is no event observed when the peer does not exist. In other words, I could not get the pollout event on connection failure. This logic works fine with TCP sockets on both Solaris and Suse10.
    I am working with SCTP one-to-one style sockets.
    Is there any way to handle this issue?
    Do I need to load any patch to resolve this issue?
    It will be great if I get a solution in this regard.
    Thanks in advance.
    Best Regards,
    Bipin.

    There are at least two problems here.
    A. In the receiver you should test for -1 from the read() immediately, rather than continue with the loop and try to write -1 bytes to the file.
    B. In the sender you are ignoring the return value of client.write(), which can be anything from 0 to the buffer length. If you get 0 you should wait for another OP_WRITE to trigger; if you get a 'short write' you need to retry it until you've got nothing left to write from the current buffer, before you read any more data. This is where the data is vanishing.

  • OCCI and non-blocking

    I'd like to use the OCCI interface in a non-blocking mode. Does anyone have any experience with this? Looks like I need to use a combo of OCI and OCCI calls to set the OCI_HTYPE_SERVER handle with the OCI_ATTR_NONBLOCKING MODE. However, my stmt->executeQuery() method seems to be throwing an exceptions, which I would have though would have been the OCI_STILL_EXECUTING error, but it's not. The exeception is an "ORA-32103 error from OCI call". If I continue to do another stmt->executeQuery(), I eventually get an access exception.
    Anyone have any code snippets using OCCI in non-blocking mode?

    I use threads. ACE/TAO to be precise.
    I have singleton class that manages the Oracle environment and connection as well as being a statement
    factory.
    Just have a thread perform your stmt->executeXXX() method and you will not need to worry about non-blocking.
    That's how I do it and it works well.

  • Non-Blocking Multicast Sockets in JDK 1.4?

    Hi,
    I've been trying to create non-blocking multicast sockets in JDK1.4, which essentially seems (at this stage) to boil down to the simpler problem of creating a DatagramChannel that uses MulticastSockets, or at least DatagramSockets that can join a Multicast group. Not having found any obvious way to do it, I created this extraordinary hack:
    package java.net; // Wicked, wicked!
    import java.io.*;
    public class MyDatagramSocket {
    public static void join(java.net.DatagramSocket socket, InetAddress addr)
    throws IOExceptio DatagramSocket ds = new DatagramSocket(port);
    ds.setReuseAddress(true);
    MyDatagramSocket.join(ds, InetAddress.getByName("224.0.0.104"));
    DatagramPacket dp = new DatagramPacket(array, 5000);
    ds.receive(dp);          /* READS FINE */
    n
    socket.impl.join(addr); // Uses knowledge of DatagramSocket culled from examining source to access DatagramSocketImpl
    Now I compile this, and drop the class file into my rt.jar files (in the JDK and the JRE), so that I can use MyDatagramSocket.join (DatagramSocket, InetAddress), which looks like it should work from code like this:
    try {
    int port = 58501;
    DatagramChannel dc = DatagramChannel.open();
    dc.socket().setReuseAddress(true);
    dc.socket().bind(new InetSocketAddress(port));
    MyDatagramSocket.join(dc.socket(), InetAddress.getByName("224.0.0.104"));
    byte [] array = new byte[5000];
    ByteBuffer bb = ByteBuffer.wrap(array);
    dc.receive(bb);
    System.out.println("Read from dc");
    } catch (Exception x) {
    x.printStackTrace();
    But it doesn't work - it just doesn't read. A simpler example is this:
    DatagramSocket ds = new DatagramSocket(port);
    ds.setReuseAddress(true);
    MyDatagramSocket.join(ds, InetAddress.getByName("224.0.0.104"));
    DatagramPacket dp = new DatagramPacket(array, 5000);
    ds.receive(dp);          /* READS FINE */
    So I know that my hack is working, but this fails:
    DatagramChannel dc = DatagramChannel.open();
    dc.socket().bind(new InetSocketAddress(port));
    dc.socket().setReuseAddress(true);
    MyDatagramSocket.join(dc.socket(), InetAddress.getByName("224.0.0.104"));
    DatagramPacket dp = new DatagramPacket(array, 5000);
    dc.socket().receive(dp);     /* NEVER READS */
    I've reduced the problem to one of the difference between a java.net.DatagramSocket - the standard DatagramSocket, and a sun.nio.ch.DatagramSocketAdaptor, which is what DatagramChannels seem to use.
    My questions are:
    a) Is there a proper way to do this, without my adding my own classes to java.net?
    b) If NO is the answer to a), any ideas what I'm doing wrong in my code?
    Many thanks for any assistance,
    Craig

    I've encountered the same problem in my code. The datagramChannel never receives incoming data. Doesn't matter the rate at which you send it or anything else. I don't see any way around this problem at the moment. If i find something i'll post it. Interesting enough, my friend who programs with C++ got non-blocking I/O with datagrams to work in windows. So this might just be java.

  • 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

  • Non-blocking SocketChannel and close - huh?

    It looks like closing a socketchannel that is in non-blocking mode can result in a dead drop of the connection, with some bytes that have already been sent and accepted (as in, 'consumed' from the buffer) being completely dropped.
    In fact, I'm generally confused: Actual C non-blocking code has a similar setup for 'close' as you can see in SocketChannel's OP_CONNECT behaviour - just because you want to connect the socket doesn't mean it magically happends without blocking. Wait for a ready flag, then try again.
    It should work the same way with close (you try to close, but it may not be possible without blocking).
    Is this a huge gaping bug that no one quite figured out just yet, or did I miss something? I loathe to turn on linger, as that's just a crapshoot (you never know if it actually gets through. You could run into funny surprises once the server gets a bit busy. I'd rather not) and tends to cause massive leaks on linux, at least according to some google searches.
    There seems to be slightly better performance (in that I have always received all data sofar) if I close the socket instead of the channel (socketChannel.socket().close() instead of socketChannel.close()) - but this has been a random attempt at 'making it work', and I can't find any documentation that backs up that this will DEFINITELY not lose any information without letting me know somehow. That still sounds impossible with this approach.

    Actual C non-blocking code has a similar setup for
    'close' as you can see in SocketChannel's
    OP_CONNECT behaviour ...No it doesn't. I don't know what you mean by this.
    Closing a socket is asynchronous, but it shouldn't lose any data - if the data can be delivered it will be, followed by the FIN. You don't know when it is delivered, and you don't get to hear about any errors such as an RST coming from the other end, say if it decided to close before reading all the data, or if some intermediate router hung you up.
    I'm wondering if you are really dealing with all the short write and zero length write possibilities, i.e. whether the data isn't really still in your output buffer. Don't wish to teach you to suck eggs but there are some subtleties here.
    Setting a positive linger timeout doesn't really help because Java doesn't tell you if the timeout expired. (I only asked for this about four years ago). You get to wait while any pending data is delivered, but you still have to guess about whether it all went or the timeout expired, and the behaviour after the timeout expires is platform-dependent: some (Windows) issue an RST, others (Unix) keep trying.
    Blocking or non-blocking mode shouldn't make any difference to this (except that Linux will block on a positive linger timeout even in non-blocking mode, which is wrong), and whether you close the channel or the socket is immaterial as one calls the other anyway.
    The reason why OP_CONNECT is different in blocking/non-blocking modes is that in blocking mode it won't return until the SYN-ACK is received, while in non-blocking mode it just sends the SYN and relies on you calling connect() again (at the C level) to collect the SYN-ACK, or not - this is what finishConnect() tells you.
    tends to cause massive leaks on linux, at least
    according to some google searchesIt can't, unless you are referring to the Helix client thing, which appears to be just a badly designed C++ class library with, for some reason, its own linger implementation outside the kernel.

Maybe you are looking for

  • HT5085 iTunes match in different country than apple id

    I have an account in the US iTunes store with no credit card on file. I use only iTunes cards. Will I be able to use iTunes Match subscribing in a country different than the US Thxs

  • Adding Metadata to JPEG, EPS, PSD, TIFF

    Hi all, I would like to know how if is possible to a read and write metadata (basically Caption and Kewords fields) to a different kind of files (EPS with JPEG compression, TIFF, JPEG, PSD...) WITHOUT opening them in Photoshop. I need to manage all f

  • Report counterpart sample for   field = select(max)

    Post Author: JuneCruz CA Forum: Crystal Reports Hi Guys, This the contenct of my table. NFstCol NSndCol NTrdCol - 1       One     12       One     13       One     14       Two     15       Two     16       Two     17       One     28       One     2

  • Public instance variable vs. accessor method

    I know some OOP purists believe all instance variables should be private, and if there's a need to view or set the value of these instance variable, public accessor methods need to be created. Data encapsulation is the driving force behind this belie

  • PSE 9 Mac-I switched to a smaller monitor and can't determine how to shrink the window.

    I recently changed monitors from a 28" Cinema display to a 23" Cinema display (Mac) and discovered that the window is still being displayed for the larger monitor which means that the pallettes that are displayed on the right cannot be seen. How do I