Detect loss of socket connection using java.nio.channels.Selector

I'm using the nio package to write a "proxy" type application, so I have a ServerSocketChannel listening for incoming connections from a client and then create a SocketChannel to connect to a server. Both SocketChannels are registered to the same Selector for OP_READ requests.
All works fine, until either the client or server drops the connection. How can I detect this has happened, so my proxy app can drop the other end of the connection ?
The Selector.select() method is not triggered by this event. I have tried using Selector.select(timeout) and then checking the status of each channel, but they still show isConnected()=true.
Thanks,
Phil Blake

Please don't cross post.
http://forum.java.sun.com/thread.jsp?thread=184411&forum=4&message=587874

Similar Messages

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

  • Need an example of how to use java.nio.channels.FileLock

    Hi,
    I need to use the Filelock, but can�t find any examples on how to implement it -
    is it still used in Java 5.0?

    Would this be the correct way to check whether the file is already locked?
    public static void main(String[] args) throws Exception {
         FileOutputStream fos = new FileOutputStream("data.txt");
         FileLock fl = fos.getChannel().tryLock();
         if (fl != null) {
         System.out.println("Locked File");
         Thread.sleep(30000);
         fl.release();
         System.out.println("Released Lock");
         else{
              System.out.println("File is already locked!");
         fos.close();
         }

  • Java.nio.channels.FileChannel jar file

    Hi
    I have used java.nio.channels.FileChannel package in my program.
    where can I get the jar file which has the above package?
    Thanx

    i give here sample code.. use this it will work fine..
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    public class copyImage
    public static void main(String [] args) throws IOException
    try {
    // Create channel on the source
    FileChannel srcChannel = new FileInputStream("dragonfly.jpg").getChannel();
    FileChannel dstChannel =new FileOutputStream("1.jpg").getChannel();
    // Copy file contents from source to destination
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    // Close the channels
    srcChannel.close();
    dstChannel.close();
    } catch (IOException e) {
    }

  • Java.nio.channels.ClosedChannelException using https

    Hello,
    I have deployed an application to the OC4J 10.1.3.40, it runs well as long as it is used by http. Since it is running under https an error comes randomly.
    Here is the text from the log.xml:
    <MSG_TEXT>Exception in NIOServerSocketDriver:selectForRead</MSG_TEXT>
    <SUPPL_DETAIL><![CDATA[java.nio.channels.ClosedChannelException
         at java.nio.channels.spi.AbstractSelectableChannel.configureBlocking(AbstractSelectableChannel.java:252)
         at oracle.oc4j.network.NIOServerSocketDriver$SelectorThreadTask.selectForRead(NIOServerSocketDriver.java:331)
         at oracle.oc4j.network.NIOServerSocketDriver.selectForRead(NIOServerSocketDriver.java:58)
         at oracle.oc4j.network.ServerSocketAcceptHandler.persistConnection(ServerSocketAcceptHandler.java:389)
         at oracle.oc4j.network.ServerSocketAcceptHandler.endReadHandlerRun(ServerSocketAcceptHandler.java:409)
         at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:275)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:619)
    ]]></SUPPL_DETAIL>
    Can anybody help me?
    Regards
    Jens

    Jens,
    Can you turn up your debug level to FINEST? It appears that during the read operation an attempt to access a channel closed to read occurs.
    // Create binding -- set binding properties before you open the factory.
    OracleDBBinding odbBinding = new OracleDBBinding();
    // Create address.
    EndpointAddress odbAddress = new EndpointAddress("oracledb://ADAPTER/");
    // Create channel factory from binding and address.
    ChannelFactory<IRequestChannel> factory =
        new ChannelFactory<IRequestChannel>(odbBinding, odbAddress);
    // Specify credentials.
    factory.Credentials.UserName.UserName = "SCOTT";
    factory.Credentials.UserName.Password = "TIGER";
    // Open factory
    factory.Open();
    // Get channel and open it.
    IRequestChannel channel = factory.CreateChannel();
    channel.Open();-Michael

  • Socket connection between Java and C

    I want to establish socket connection between Java client and C server (on Unix). Can anybody tell how to do it? Will the socket created in client be available in server. I tried out but there was no response from the server.

    We too can't connect the daemon server written by "c". The phenomena is below.
    << Execution of this Question1.class >> ---------------------------------------
    [kazuyuki@CryptOne tmp]$ java Question1 E 1.2.3.4 MFrame.java 195.211.1.1 15021
    << Output message >> ----------------------------------------------------------
    Quetion1 : flg_ = E
    Quetion1 : key_ = 1.2.3.4
    Quetion1 : fn_ = MFrame.java
    Quetion1 : adr_ = CryptOne.localhost/195.211.1.1
    Quetion1 : port_ = 15021
    java.net.ConnectException: Connection refused
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:350)
         at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:137)
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:124)
         at java.net.Socket.<init>(Socket.java:268)
         at java.net.Socket.<init>(Socket.java:122)
         at Question1.UPLOAD(Question1.java:65)
         at Question1.main(Question1.java:155)
    << Question >> ----------------------------------------------------------------
    Why the event "java.net.ConnectException: Connection refused" has occured ?
    The server to connect from Question1 can accept the connection request from
    the client program coded by "c" program. We have written down the daemon server
    program by "c" code tcp/ip socket functions (socket, bind, listen, accept).
    Security manager admits the access from this Question1.class, we have checked.
    Would you like please answer this Connction refuse occurrence ?
                                                                     2002.05.18 11:50:00.0(JST)
                                                                     K.Masuda
    << Java client code>> -------------------------------------------------
         (c)Copyright     All rights reserved.
              K.Masuda     2002.05.18
                   << Question1.java >>
    import     java.lang.String;
    import     java.io.InputStream;
    import     java.io.OutputStream;
    import     java.io.DataInputStream;
    import     java.io.DataOutputStream;
    import     java.io.FileInputStream;
    import     java.io.FileOutputStream;
    import     java.io.IOException;
    import     java.io.FileNotFoundException;
    import     java.net.Socket;
    import     java.net.InetAddress;
    import     java.net.UnknownHostException;
    import     java.net.ConnectException;
    import     java.net.NoRouteToHostException;
    class Question1 {
         char               flg_;
         String               key_;
         String               fn_;
         InetAddress          adr_;
         int                    port_;
         Socket               sock_;
         Question1(
              char          flg,
              String          key,
              String          fn,
              String          adr,
              int               port
              flg_     = flg;     
              key_     = key;
              fn_          = fn;
              try{
                   adr_     = InetAddress.getByName( adr );
              catch( UnknownHostException e ){
                   e.printStackTrace();
              port_     = port;
    System.out.println( "Quetion1 : flg_ = " + flg_ );
    System.out.println( "Quetion1 : key_ = " + key_ );
    System.out.println( "Quetion1 : fn_ = " + fn_ );
    System.out.println( "Quetion1 : adr_ = " + adr_ );
    System.out.println( "Quetion1 : port_ = " + port_ );
         public void UPLOAD(
              try{
                   sock_     = new Socket( adr_, port_ );
                   UpLoad();
                   DnLoad();
                   sock_.close();
              catch( UnknownHostException e ){
                   e.printStackTrace();
              catch( ConnectException e ){
                   e.printStackTrace();
              catch( NoRouteToHostException e ){
                   e.printStackTrace();
              catch( IOException e ){
                   e.printStackTrace();
         public void UpLoad(
              byte[]                         buf          = new byte[ 512 ];
              int                              rlen;
              int                              wlen;
              try {
                   OutputStream          sos          = sock_.getOutputStream();
                   FileInputStream          fis          = new FileInputStream( fn_ );
                   DataInputStream          dis          = new DataInputStream( fis );
                   DataOutputStream     dos          = new DataOutputStream( sos );
                   while( ( rlen =     dis.read( buf, 0, buf.length ) ) >= 0 ){
                        dos.write( buf, 0, rlen );
                   dis.close();
                   dos.close();
                   fis.close();
                   sos.close();
              catch( IOException e ){
                   e.printStackTrace();
         public void DnLoad(
              byte[]                         buf          = new byte[ 512 ];
              int                              rlen;
              int                              wlen;
              try {
                   InputStream               sis          = sock_.getInputStream();
                   FileOutputStream     fos          = new FileOutputStream( fn_ + ".cry" );
                   DataInputStream          dis          = new DataInputStream( sis );
                   DataOutputStream     dos          = new DataOutputStream( fos );
                   while( ( rlen =     dis.read( buf, 0, buf.length ) ) >= 0 ){
                        dos.write( buf, 0, rlen );
                   dis.close();
                   dos.close();
                   fos.close();
                   sis.close();
              catch( IOException e ){
                   e.printStackTrace();
         public static void main(
              String[] args
              char[]     chrs     = ( new String( args[ 0 ] ) ).toCharArray();
              Question1     clnt     = new Question1(
                                                                     // E or D
                                            chrs[ 0 ],
                                            args[ 1 ],               // key string
                                            args[ 2 ],               // file to be processed
                                            args[ 3 ],               // IP address
                                                                     // port
                                            Integer.parseInt( args[ 4 ] )
              clnt.UPLOAD();
    }

  • Using java.nio

    I have copied this, one program from a book that would have to read file of gives to me to you mixed but it does not work, you could me why?
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    public class ReadPrimesMixedData {
    public static void main(String[] args) {
    File aFile = new File("C:/Beg Java Stuff/primes.txt");
    FileInputStream inFile = null;
    try {
    inFile = new FileInputStream(aFile);
    } catch(FileNotFoundException e) {
    e.printStackTrace(System.err);
    System.exit(1);
    FileChannel inChannel = inFile.getChannel();
    try {
    ByteBuffer lengthBuf = ByteBuffer.allocate(8);
    int strLength = 0; // Stores the string length
    ByteBuffer buf = null; // Stores a reference to the second byte buffer
    byte[] strChars = null; // Stores a reference to an array to hold the string
    while(true) {
    if(inChannel.read(lengthBuf) == -1) // Read the string length, if its EOF
    break; // exit the loop
    lengthBuf.flip();
    strLength = (int)lengthBuf.getDouble(); // Extract the length and convert to int
    buf = ByteBuffer.allocate(strLength+8); // Buffer for the string & the prime
    if(inChannel.read(buf) == -1) {            // Read the string & binary prime value
    assert false; // Should not get here!
    break; // Exit loop on EOF
    buf.flip();
    strChars = new byte[strLength]; // Create the array for the string
    buf.get(strChars); // Extract string & binary prime value
    System.out.println("String length: " + strChars.length+ " String: " +
    new String(strChars) + " Binary value: " + buf.getLong());
    lengthBuf.clear(); // Clear the buffer for the next read
    System.out.println("\nEOF reached.");
    inFile.close(); // Close the file and the channel
    } catch(IOException e) {
    e.printStackTrace(System.err);
    System.exit(1);
    System.exit(0);
    This e' the program that writes the file
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.FileChannel;
    public class PrimesToFile2 {
    public static void main(String[] args) {
    int primesRequired = 100; // Default count
    if (args.length > 0) {
    try {
    primesRequired = Integer.valueOf(args[0]).intValue();
    } catch (NumberFormatException e) {
    System.out.println("Prime count value invalid. Using default of "
    + primesRequired);
    long[] primes = new long[primesRequired]; // Array to store primes
    primes[0] = 2; // Seed the first prime
    primes[1] = 3; // and the second
    // Count of primes found - up to now, which is also the array index
    int count = 2;
    long number = 5; // Next integer to be tested
    outer:
    for (; count < primesRequired; number += 2) {
    // The maximum divisor we need to try is square root of number
    long limit = (long) Math.ceil(Math.sqrt((double) number));
    // Divide by all the primes we have up to limit
    for (int i = 1; i < count && primes[i] <= limit; i++)
    if (number % primes[i] == 0) // Is it an exact divisor?
    continue outer; // yes, try the next number
    primes[count++] = number; // We got one!
    File aFile = new File("C:/Beg Java Stuff/primes.txt");
    FileOutputStream outputFile = null;
    try {
    outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
    e.printStackTrace(System.err);
    System.exit(1);
    FileChannel file = outputFile.getChannel();
    final int BUFFERSIZE = 100; // Buffer size in bytes
    ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    DoubleBuffer doubleBuf = buf.asDoubleBuffer();
    buf.position(8);
    CharBuffer charBuf = buf.asCharBuffer();
    LongBuffer longBuf = null;
    String primeStr = null;
    for (int i = 0; i < primes.length; i++) {
    primeStr = "prime = " + primes; // Create the string
    doubleBuf.put(0,(double) primeStr.length());// Store the string length
    charBuf.put(primeStr); // Store the string
    buf.position(2 * charBuf.position() + 8); // Position for 3rd buffer
    longBuf = buf.asLongBuffer(); // Create the buffer
    longBuf.put(primes[i]); // Store the binary long value
    buf.position(buf.position() + 8); // Set position after last value
    buf.flip(); // and flip
    try {
    file.write(buf); // Write the buffer as before.
    } catch (IOException e) {
    e.printStackTrace(System.err);
    System.exit(1);
    buf.clear();
    doubleBuf.clear();
    charBuf.clear();
    try {
    System.out.println("File written is " + file.size() + " bytes.");
    outputFile.close(); // Close the file and its channel
    } catch (IOException e) {
    e.printStackTrace(System.err);
    System.exit(1);
    System.exit(0);
    This works correctly

    I don't have problems when I compile the program but if I run the program ....I have this
    String length: 9 String: prim Binary value: 7277852183226228736
    String length: 0 String: Binary value: 162166969980682240
    String length: 0 String: Binary value: 7854388801345436928
    String length: 0 String: Binary value: 3573983215616
    Stjava.lang.IllegalArgumentException
    at java.nio.ByteBuffer.allocate(ByteBuffer.java:303)
    at ReadPrimesMixedData.main(ReadPrimesMixedData.java:35)
    ring length: 0 String: Binary value: 7566167222444367872
    String length: 0 String: Binary value: 88089088
    String length: 0 String: Binary value: 8214681170873443584
    String length: 0 String: Binary value: 1856
    String length: 0 String: Binary value: 8070575878335130880
    Exception in thread "main"

  • File Locking using java.nio package

    I am trying to lock a file using FileChannel's lock method on a CIFS file system. My application is on windows and the CIFS is accessed using UNC format ( \\1.2.3.4\blah.. ). I get the following error
         java.io.IOException: The network request is not supported
         at sun.nio.ch.FileChannelImpl.lock0(Native Method)
         at sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:750)
         at java.nio.channels.FileChannel.lock(FileChannel.java:865)
    From the same machine using the same UNC formatm, when I lock the file using windows C API, I can successfull lock.
    Anyone has any idea why JVM can not lock even using nio package. Shouldnt it use the same ( or similar ) API under the hood as its clear by the package name java.nio
    The C program I am using is
    #include <io.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <sys/locking.h>
    #include <share.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void main( int argc, char **argv )
    int fh,numread;
    char buffer[40];
    char filename[500];
    /* Quit if can't open file or system doesn't
    * support sharing.
    if ( argc > 1 )
              strcpy(filename,argv[1]);
    else
              strcpy(filename,"locking.c");
    fh = sopen(filename , O_RDWR, SHDENYNO, //_SH_DENYRW,
    SIREAD | SIWRITE );
    if( fh == -1 )
    exit( 1 );
    /* Lock some bytes and read them. Then unlock. */
    if( locking( fh, LKNBLCK, 30L ) != -1 )
    printf( "No one can change these bytes while I'm reading them\n" );
    numread = _read( fh, buffer, 30 );
    printf( "%d bytes read: %.30s\n", numread, buffer );
    lseek( fh, 0L, SEEK_SET );
         printf( "Press a key to unlock the file.....\n" );
         getchar();
         locking( fh, LKUNLCK, 30L );
    printf( "Now I'm done. Do what you will with them\n" );
    else
    perror( "Locking failed\n" );
    _close( fh );
    }

    It uses LockFile and LockFileEx. Please check in the MSDN documentation the peculiarities of such APIs.
    JNIEXPORT jint JNICALL
    Java_sun_nio_ch_FileChannelImpl_lock0(JNIEnv *env, jobject this, jobject fdo,
                                          jboolean block, jlong pos, jlong size,
                                          jboolean shared)
        jint fd = fdval(env, fdo);
        HANDLE h = (HANDLE)_get_osfhandle(fd);
        DWORD lowPos = (DWORD)pos;
        long highPos = (long)(pos >> 32);
        DWORD lowNumBytes = (DWORD)size;
        DWORD highNumBytes = (DWORD)(size >> 32);
        jint result = 0;
        if (onNT) {
            DWORD flags = 0;
            OVERLAPPED o;
            o.hEvent = 0;
            o.Offset = lowPos;
            o.OffsetHigh = highPos;
            if (block == JNI_FALSE) {
                flags |= LOCKFILE_FAIL_IMMEDIATELY;
            if (shared == JNI_FALSE) {
                flags |= LOCKFILE_EXCLUSIVE_LOCK;
            result = LockFileEx(h, flags, 0, lowNumBytes, highNumBytes, &o);
            if (result == 0) {
                int error = GetLastError();
                if (error != ERROR_LOCK_VIOLATION) {
                    JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                    return sun_nio_ch_FileChannelImpl_NO_LOCK;
                if (flags & LOCKFILE_FAIL_IMMEDIATELY) {
                    return sun_nio_ch_FileChannelImpl_NO_LOCK;
                JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                return sun_nio_ch_FileChannelImpl_NO_LOCK;
            return sun_nio_ch_FileChannelImpl_LOCKED;
        } else {
            for(;;) {
                if (size > 0x7fffffff) {
                    size = 0x7fffffff;
                lowNumBytes = (DWORD)size;
                highNumBytes = 0;
                result = LockFile(h, lowPos, highPos, lowNumBytes, highNumBytes);
                if (result != 0) {
                    if (shared == JNI_TRUE) {
                        return sun_nio_ch_FileChannelImpl_RET_EX_LOCK;
                    } else {
                        return sun_nio_ch_FileChannelImpl_LOCKED;
                } else {
                    int error = GetLastError();
                    if (error != ERROR_LOCK_VIOLATION) {
                        JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                        return sun_nio_ch_FileChannelImpl_NO_LOCK;
                    if (block == JNI_FALSE) {
                        return sun_nio_ch_FileChannelImpl_NO_LOCK;
                Sleep(100);
        return sun_nio_ch_FileChannelImpl_NO_LOCK;
    }

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

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

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

  • Java.nio.channels.IllegalBlockingModeException

    I am using selector for read and PrintWriter writer = new PrintWriter(new OutputStreamWriter(sc.getOutputStream()),true) for writing to the socket and I get this exception at write statement. Can anyone suggest me what should I do??
    java.nio.channels.IllegalBlockingModeException
    at java.nio.channels.Channels.write(Channels.java:59)
    at java.nio.channels.Channels.access$000(Channels.java:47)
    at java.nio.channels.Channels$1.write(Channels.java:134)
    at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:334)
    at sun.nio.cs.StreamEncoder$CharsetSE.implFlushBuffer(StreamEncoder.java
    :402)
    at sun.nio.cs.StreamEncoder$CharsetSE.implFlush(StreamEncoder.java:406)
    at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:150)
    at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:213)
    at java.io.PrintWriter.newLine(PrintWriter.java:256)
    at java.io.PrintWriter.println(PrintWriter.java:405)
    at java.io.PrintWriter.println(PrintWriter.java:516)
    at SktChannelTest3.run(SktChannelTest3.java:91)

    Hi,
    Thanx for the reply. I am using Selecotor for read and if it timesout I used PrintWriter to write to Socket ( Not socket channel). So, once it comes out of select loop, it'd excecute PrintWriter.println("Timeout message....") statement. And at this statement I/m getting exception.

  • DPS 11.1.1.5.0 java.nio.channels.ClosedChannelException

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

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

  • Java.nio.channels.Pipe?

    Someone explain what java.nio.channels.Pipe should be uses for, and how to use it?

    You can use this class to transfer the content of a channel from one thread to another thread.
    The writing thread blocks when the pipe is full.
    package com.desoft.pipetest;
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    public class PipeTest {
    public static void main (String args[])
    try
    FileInputStream fis = new FileInputStream(args[0]);
    FileChannel fc = fis.getChannel();
    Pipe p = Pipe.open();
    PipeReader pr = new PipeReader( p );
    Thread t = new Thread( pr );
    t.start();
    fc.transferTo(0, fc.size(), p.sink() );
    catch( IOException ioe )
    ioe.printStackTrace();
    * Read from a Pipe and write Content to System.out
    static class PipeReader implements Runnable
    Pipe p;
    public PipeReader( Pipe p )
    this.p = p;
    public void run()
    try
    ByteBuffer buffer = ByteBuffer.allocate( 10 );
    int len = 0;
    while( (len=p.source().read( buffer )) > 0 )
    buffer.rewind();
    for( int i = 0; i < len; i++ )
    System.out.print( (char)buffer.get());
    buffer.rewind();
    catch( IOException ioe )
    ioe.printStackTrace();

  • Java.nio.channels.NonWritableChannelException

    i have been facing this exception, please tell me how to remove it
    java.nio.channels.NonWritableChannelException
    here is my code
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    public class abc
         public static void main(String arg[])
              try
              File ff=new File("aaa.txt");
              FileInputStream fis=new FileInputStream(ff);
              FileChannel fc=fis.getChannel();
              FileLock lock=fc.lock();
              lock.release();
              fc.close();
              catch(Exception e)
                   System.out.println("hello22"+e);
    }

    what should i do then to make the channel writable . please tell me what to change in the code, i just want to lock the file and after that i will modify it.

  • Socket example using Java 5

    Last year I posted 4 programs that provided a simple client server using both stream sockets and NIO. I decided as an exercise in using Java 5 to port that code and try to use as many of the new features as possible. The following code is very long and does what all the previous example programs did. In replies do not repost the whole of this message.
    It provides a simple chat like client and server. The user can request either a stream connection or a NIO connection or provide one of their own.
    //========================== MsgSwitch.java ===========================//
    package pkwnet.msgswitch;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    import java.util.logging.Handler;
    * main class for message switch
    * command line arguments are
    * -p port number for server
    * -s run server
    * -a server ip address including port for client
    * -i idle timer in seconds
    * -n use NIO
    * -c specify connection class
    public class MsgSwitch {
        static private int errors = 0;
        static private String address = "127.0.0.1:6060";
        static private String connectionClass = "pkwnet.msgswitch.StreamConnection";
        static public void main(String [] args) {
            int port = 6060;
            int idleTime = 600;
            boolean server = false;
            boolean nio = false;
            Logger logger = Logger.getLogger("msgswitch");
            for(String arg : args) {
                if(arg.startsWith("-a")) {
                    address = arg.substring(2);
                } else if(arg.startsWith("-p")) {
                    port = argToInt(arg);
                    server = true;
                } else if(arg.startsWith("-i")) {
                    idleTime = argToInt(arg);
                } else if (arg.startsWith("-s")) {
                    server = true;
                } else if (arg.startsWith("-c")) {
                    connectionClass = arg.substring(2);
                } else if (arg.startsWith("-n")) {
                    connectionClass = "pkwnet.msgswitch.NIOConnection";
                } else {
                    String err = "unknown argument=" + arg;
                    logger.severe(err);
                    System.err.println(err);
                    errors++;
            if (errors == 0) {
                if (server) {
                    new Server().listen(port,idleTime, nio);
                } else {
                    new Client().start(address, nio);
            } else {
                fail(errors + " errors encountered", null);
        static private int argToInt(String arg) {
            int val = 0;
            try {
                val = Integer.parseInt(arg.substring(2));
            } catch (NumberFormatException e) {
                String err = "invalid argument format: " + arg;
                Logger.getLogger("msgswitch").severe(err);
                System.err.println(err);
                errors++;
            return val;
        static public void fail(String err, Throwable e) {
            String msg = "Operation terminated: " + err;
            Logger.getLogger("msgswitch").log(Level.SEVERE, msg, e);
            System.err.println(msg);
            System.exit(12);
        static public Connection getConnection() {
            Connection conn = null;
            try {
                conn = (Connection) Class.forName(connectionClass).newInstance();
            } catch (Exception e) {
                fail ("connection class error", e);
            return conn;
        static public void logCaller(Logger logger, Level level) {
            String text = "CALLED";
            if (logger.isLoggable(level)) {
                try {
                    throw new Exception("logging stack");
                } catch (Exception e) {
                    StackTraceElement [] st = e.getStackTrace();
                    if (st.length > 1) {
                        text += formatElement(st[1]);
                    if (st.length >2) {
                        text += formatElement(st[2]);
                logger.log(level, text);
        static private String formatElement(StackTraceElement ste) {
            return "\n    " + ste.getClassName() + "." + ste.getMethodName()
                + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
    //================= Client.java =============================================//
    package pkwnet.msgswitch;
    * a simple Swing chat GUI using Java 5 and sockets.
    * @author PKWooster
    * @version 1.0 August 31,2005
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JDialog;
    import javax.swing.SwingUtilities;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import static java.awt.BorderLayout.*;
    client GUI class
    public class Client extends JFrame implements ConnectionListener {
         // swing GUI components
         private JTextField userText = new JTextField(40);
         private JTextArea sessionLog = new JTextArea(24,40);
         private JTextField statusText = new JTextField(40);
         private JPanel outPanel = new JPanel();
         private JScrollPane sessionLogScroll = new JScrollPane(sessionLog);
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem startItem = new JMenuItem("Start");
         private JMenuItem hostItem = new JMenuItem("Host");
         private JMenuItem aboutItem = new JMenuItem("About");
         private JMenuItem abortItem = new JMenuItem("Abort");
         private JMenuItem exitItem = new JMenuItem("Exit");
         private JMenu fileMenu = new JMenu("File");
         private JMenu helpMenu = new JMenu("Help");
         private Container cp;
         private String address;
        private Connection connection;
        private boolean sendReady = false;
        private boolean nio = false;
         Client() {
        public void start(String address, boolean nio) {
            this.address = address;
            this.nio = nio;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    runClient();
        private void runClient() {   
            connection = MsgSwitch.getConnection();
            connection.addConnectionListener(this);
              buildMenu();
              cp = getContentPane();
              sessionLog.setEditable(false);
              outPanel.add(new JLabel("Send: "));
              outPanel.add(userText);
              // enter on userText causes transmit
              userText.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){userTyped(evt);}
              cp.setLayout(new BorderLayout());
              cp.add(outPanel,NORTH);
              cp.add(sessionLogScroll,CENTER);
              cp.add(statusText,SOUTH);
              setStatus("Closed");
              addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    mnuExit();
              pack();
            setVisible(true);
    * attempt to send the contents of the user text field
        private void userTyped(ActionEvent evt) {
            if (sendReady) {
                String txt = evt.getActionCommand()+"\n";
                userText.setText("");
                toSessionLog("> ", txt);
                sendReady = false;
                connection.send(txt);
    * append text to the session log
         private void toSessionLog(String prefix, String txt) {
              sessionLog.append(prefix + txt);
              sessionLog.setCaretPosition(sessionLog.getDocument().getLength() ); // force last line visible
    * build the standard menu bar
         private void buildMenu()
              JMenuItem item;
              // file menu
              startItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuStart();}});
              fileMenu.add(startItem);
              hostItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuHost();}});
              fileMenu.add(hostItem);
              exitItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuExit();}});
              fileMenu.add(exitItem);
              menuBar.add(fileMenu);
              helpMenu.add(aboutItem);
              aboutItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuAbout();}});
              menuBar.add(helpMenu);
              setJMenuBar(menuBar);
    * start and stop communications from start menu
         private void mnuStart() {
            if(connection.getState() ==  Connection.State.CLOSED) {
                connection.connect(address);
            } else {
                connection.disconnect();
    *  prompt user for host in form address:port
        private void mnuHost() {
              String txt = JOptionPane.showInputDialog("Enter host address:port", connection.getAddress());
              if (txt == null)return;
            address = txt;
         private void mnuAbout() {
              JDialog dialog = new JDialog(this, "About Client");
              JTextField text = new JTextField("Simple character client");
            dialog.getContentPane().add(text);
            dialog.pack();
            dialog.setVisible(true);
         // exit menu
         private void mnuExit() {
            exit();
        private void exit() {
              connection.disconnect();
              System.exit(0);
         private void setStatus(String st) {
            statusText.setText(st);
         private void setStatus(Connection.State state) {
            switch(state) {
                case OPENED:
                    startItem.setText("Stop");
                    setStatus("Connected to "+address);
                    break;
                case CLOSED:
                    startItem.setText("Start");
                    setStatus("Disconnected");
                    break;
                case OPENING:
                    setStatus("Connecting to "+address);
                    startItem.setText("Abort");
                    break;
                case CLOSING:
                    setStatus("Disconnecting from "+address);
                    startItem.setText("Abort");
                    break;
        public void stateChanged(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
        public void dataAvailable(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    String txt = event.getData();
                    if (txt == null) {
                        txt = "$null$";
                    toSessionLog("< ", txt + "\n");   
        public void sendAllowed(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    sendReady = true;
        public void accept(ConnectionEvent event) {
    //========================== Server.java ===============================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    * a simple message switch using stream based socket i/o
    * a very simple text message switching program
    * user commands start with $ and consist of blank seperated arguments
    * other lines sent by the user are forwarded
    * $on nickname targets
    *    sign on as nickname, sending to targets
    * $to targets
    *    change target list, reports current value
    * $list nicknames
    *    list status of specified nicknames
    * $list
    *    list all connected users
    * $off
    *    sign off
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class Server {
        private ConcurrentHashMap<String, User> perUser = new ConcurrentHashMap<String,User>();
        private Timer idleTimer;
        private Connection conn;
        public void listen(int port, final int idleTime, boolean nio) {
            idleTimer = new Timer();
            idleTimer.scheduleAtFixedRate(new TimerTask(){public void run(){oneSec();}},0,1000);
            conn = MsgSwitch.getConnection();
            conn.addConnectionListener(new ConnectionListener() {
                public void stateChanged(ConnectionEvent event) {
                public void dataAvailable(ConnectionEvent event) {
                public void sendAllowed(ConnectionEvent event) {
                public void accept(ConnectionEvent event) {
                    Connection uconn = event.getConnection();
                    new User(uconn, perUser, idleTime);
            conn.listen(port);
            idleTimer.cancel();
        private void oneSec() {
            Collection<User> uc = perUser.values();
            for(User u : uc) {
                u.oneSec();
    //================= User.java  ==============================================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * defines the processing for a message switch user
    * @author PKWooster
    * @version 1.0 June 15,2004
    public class User implements ConnectionListener {
        private ConcurrentHashMap<String, User> perUser;
        private String name;
        private String address;
        private boolean signedOn = false;
        private String[] targets;
        private AtomicInteger remainingTime;
        private int idleTime;
        Connection conn;
        Logger logger;
      * construct a user, link it to its connection and put it in the perUser table
        User(Connection conn, ConcurrentHashMap<String,User>p, int idle) {
            this.conn = conn;
            logger = Logger.getLogger("msgswitch.user");
            conn.addConnectionListener(this);
            address = conn.getAddress();
            logger.info("creating user " + address);
            perUser = p;
            idleTime = idle;
            remainingTime = new AtomicInteger(idleTime);
            rename(address);
            targets = new String[0];
    * process state changes
        public void stateChanged(ConnectionEvent event) {
            if(event.getState() == Connection.State.CLOSED) {
                close(false);
    * data is available, process commands and forward other data.
        public void dataAvailable(ConnectionEvent event) {
            String msg = event.getData();
            if (msg.startsWith("$")) {
                doCommand(msg);
            } else {
                forward(msg);
            remainingTime.set(idleTime);
    * do nothing for sendAllowed events
        public void sendAllowed(ConnectionEvent event) {
    * do nothing for accept events
        public void accept(ConnectionEvent event) {
    * called once per second by the server main thread.
        public void oneSec() {
            if(idleTime != 0 && 1 > remainingTime.decrementAndGet()) {
                close(true);
    * send a message
        private void send(String msg) {
            conn.send(msg);
            remainingTime.set(idleTime);
    * forward data messages to other users
    * @param txt the message to send
        private void forward(String txt) {
            txt = name+": "+txt + "\n";
            if(0 < targets.length) {
                for(String target :targets) {
                    User user = perUser.get(target);
                    if(user != null) {
                        user.send(txt);
            } else {
                for (User user : perUser.values()) {
                    if (user != this) {
                        user.send(txt);
    * execute command messages, commands start with a $
    * and contain arguments delimited by white space.
    * @param command the command string
        private void doCommand(String command) {
            boolean good = false;
            command = command.substring(1).trim();
            if(command.length() > 0) {
                String [] args = command.split("\\s+");
                if(args[0].equals("on")) {
                    good = signOn(args);
                } else if(args[0].equals("off")) {
                    good = signOff(args);
                } else if(args[0].equals("list")) {
                    good = listUsers(args);
                } else if(args[0].equals("to")) {
                    good = setTargets(args,1);
                } else if(args[0].equals("idle")) {
                    good = setIdle(args);
                if(!good) {
                    send("invalid command=" + command + "\n");
    * sign on command
        private boolean signOn(String [] args) {
            boolean good = false;
            if(args.length >1) {
                String nm = args[1];
                logger.info("signing on as: " + nm);
                if(rename(nm)) {
                    conn.setName(name);
                    send("Signed on as " + name + "\n");
                    signedOn = true;
                    good = true;
                    setTargets(args,2);
                } else {
                    send("name="+nm+" already signed on\n");
            return good;
    * set forwarding targets
        private boolean setTargets(String [] args, int start) {
            if(start < args.length) {
                targets = new String[args.length-start];
                System.arraycopy(args, start, targets, 0, targets.length);
            String str = "to=";
            for(String target : targets) {
                str += (target + " ");
            send(str+"\n");
            return true;
    * set idle timeout
        private boolean setIdle(String[] args) {
            try {
                idleTime = new Integer(args[1]).intValue();
                remainingTime.set(idleTime);
                send("idle time set to "+idleTime+"\r\n");
                return true;
            } catch(NumberFormatException exc) {
                return false;
    * sign off
        private boolean signOff(String [] args) {
            close(true);
            return true;
    * list connected users
        private boolean listUsers(String [] args) {
            TreeSet<String> allUsers = new TreeSet<String>(perUser.keySet());
            HashSet<String> t = new HashSet<String>(Arrays.asList(targets));
            LinkedList<String> users;
            String response = "On,Target,Nickname\n";
            if(args.length < 2) {
                users = new LinkedList<String>(allUsers);
            } else {
                users = new LinkedList<String>();
                for (int i = 1; i < args.length; i++) {
                    users.add(args);
    for(String username : users) {
    if(username.equals(name)) {
    response += "*,";
    } else {
    response += (allUsers.contains(username) ? "y," : "n,");
    response += (t.contains(username) ? "y," : "n,");
    response += (username + "\n");
    send(response);
    return true;
    * rename this user, first we attempt to add the new name then we remove
    * the old one. Both names will be registered for a short while.
    * @param newname the new name for this user
    * @return true if the rename was successful
    private boolean rename(String newname) {
    boolean b = false;
    logger.info("rename name="+name+" newname="+newname);
    if (name != null && name.equals(newname)) {
    b = true;
    } else if (null == perUser.putIfAbsent(newname, this)) {
    if (name != null) {
    perUser.remove(name);
    name = newname;
    b = true;
    return b;
    * delete from perUser and close our connection
    private void close(boolean disconnect) {
    logger.info("closing user "+name);
    perUser.remove(name);
    if (disconnect) {
    conn.disconnect();
    //====================== Connection.java ===============================//
    package pkwnet.msgswitch;
    import java.util.HashSet;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    public abstract class Connection {
    public enum State {CLOSED, OPENING, OPENED, CLOSING}
    private HashSet<ConnectionListener> listeners = new HashSet<ConnectionListener>();
    private State state = State.CLOSED;
    private String host = "127.0.0.1";
    private int port = 6060;
    private String name = "unconnected";
    public Connection() {
    public abstract void listen(int port);
    public abstract void connect(String address);
    public abstract void disconnect();
    public abstract void send(String message);
    public void addConnectionListener(ConnectionListener listener) {
    listeners.add(listener);
    public void removeConnectionListener(ConnectionListener listener) {
    listeners.remove(listener);
    protected void fireDataAvailable(String data) {
    for (ConnectionListener listener : listeners) {
    listener.dataAvailable(new ConnectionEvent(this, state, data));
    private void fireStateChanged() {
    for (ConnectionListener listener : listeners) {
    listener.stateChanged(new ConnectionEvent(this, state));
    protected void fireSendAllowed() {
    for (ConnectionListener listener : listeners) {
    listener.sendAllowed(new ConnectionEvent(this, state));
    protected void fireAccept(Connection conn) {
    for (ConnectionListener listener : listeners) {
    listener.accept(new ConnectionEvent(this, conn));
    protected void setState(State state) {
    if (this.state != state) {
    this.state = state;
    fireStateChanged();
    public State getState() {
    return state;
    protected void setAddress(String address) {
              int n = address.indexOf(':');
              String pt = null;
    setName(address);
    if(n == 0) {
                   host = "127.0.0.1";
                   pt = address.substring(1);
              else if(n < 0) {
                   host = address;
                   port = 5050;
              } else {
    host = address.substring(0,n);
                   pt = address.substring(n+1);
    if (pt != null) {
    try {
    port = Integer.parseInt(pt);
    } catch (NumberFormatException e) {
    port = -1;
    public String getName() {
    return name;
    public void setName(String value) {
    name = value;
    public String getAddress() {
    return host + ":" + port;
    public String getHost() {
    return host;
    public void setPort(int value) {
    port = value;
    public int getPort() {
    return port;
    //=================== ConnectionEvent.java ================================//
    package pkwnet.msgswitch;
    public class ConnectionEvent extends java.util.EventObject {
    private final String data;
    private final Connection.State state;
    private final Connection conn;
    public ConnectionEvent(Object source, Connection.State state, String data, Connection conn) {
    super(source);
    this.state = state;
    this.data = data;
    this.conn = conn;
    public ConnectionEvent(Object source, Connection.State state, String data) {
    this(source, state, data, null);
    public ConnectionEvent(Object source, Connection.State state) {
    this(source, state, null, null);
    public ConnectionEvent(Object source, Connection conn) {
    this(source, conn.getState(), null, conn);
    public Connection.State getState() {
    return state;
    public String getData() {
    return data;
    public Connection getConnection() {
    return conn;
    //============================ ConnectionListener.java ===================//
    package pkwnet.msgswitch;
    public interface ConnectionListener extends java.util.EventListener {
    public void stateChanged(ConnectionEvent event);
    public void dataAvailable(ConnectionEvent event);
    public void sendAllowed(ConnectionEvent event);
    public void accept(ConnectionEvent event);
    //============================ StreamConnection.java ===================//
    package pkwnet.msgswitch;
    import java.net.Socket;
    import java.net.ServerSocket;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.IOException;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * provides stream socket i/o of character strings
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class StreamConnection extends Connection {
    private Socket sock;
    private BufferedReader in;
    private BufferedWriter out;
    private Thread recvThread = null;
    private Thread sendThread = null;
    protected LinkedBlockingQueue<String> sendQ;
    Logger logger;
    public StreamConnection() {
    super();
    logger = Logger.getLogger("msgswitch.stream");
    sendQ = new LinkedBlockingQueue<String>();
    * open a socket and start i/o threads
    public void connect(String ipAddress) {
    setAddress(ipAddress);
    try {
    sock = new Socket(getHost(), getPort());
    connect(sock);
    } catch (IOException e) {
    logger.log(Level.SEVERE, "Connection failed to=" + ipAddress, e);
    private void connect(Socket sock) {
    this.sock = sock;
    String ipAddress = getAddress();
    try {
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    recvThread = new Thread(new Runnable() {
    public void run() {
    doRecv();
    },"Recv." + getName());
    sendThread = new Thread(new Runnable() {
    public void run() {
    doSend();
    },"Send."+getName());
    sendThread.start();
    recvThread.start();
    setState(State.OPENED);
    } catch(IOException e) {
    logger.log(Level.SEVERE, "Connection failed to="+ipAddress, e);
    public void listen(int port) {       
    StreamConnection sconn;
    setPort(port);
    try {
    ServerSocket ss = new ServerSocket(port);
    while(true) {
    Socket us = ss.accept();
    sconn = new StreamConnection();
    String ipAddress = us.getInetAddress() + ":" + us.getPort();
    sconn.setAddress(ipAddress);
    sconn.connect(us);
    fireAccept(sconn);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "listen failed", e);
    * close the socket connection
    public void disconnect() {
    logger.fine("disconnect sock=" + sock + " state="+ getState());
    if(getState() == State.OPENED) {
    setState(State.CLOSING);
    try {
    sock.shutdownOutput();
    } catch(IOException ie) {
    logger.log(Level.SEVERE, "showdown failed", ie);
    } else if(getState() != State.CLOSED) {
    try {
    sock.close();
    } catch(Exception e) {
    logger.log(Level.SEVERE, "close failed", e);
    if (sendThread.isAlive()) {
    sendThread.interrupt();
    sendQ.clear();
    setState(State.CLOSED);
    public void send(String message) {
    if (getState() == State.OPENED) {
    try {
    sendQ.put(message);
    } catch(InterruptedException e) {
    logger.log(Level.SEVERE, "sendQ put interrupted", e);
    setState(State.CLOSING);
    disconnect();
    * sets the public name of this connection
    public void setName(String name) {
    super.setName(name);
    if (sendThread != null) {
    try {
    recvThread.setName("recv." + name);
    sendThread.setName("send." + name);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "nameing threads failed", e);
    * the main loop for the send thread
    private void doSend() {
    String msg;
    boolean running = true;
    while (running) {
    if (sendQ.size() == 0) {
    fireSendAllowed();
    try {
    msg = sendQ.take();
    out.write(msg);
    out.flush();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "write failed", e);
    setState(State.CLOSING);
    disconnect();
    running = false;
    * the main loop for the receive thread
    private void doRecv() {
    String inbuf;
    while (getState() == State.OPENED) {
    try {
    inbuf = in.readLine();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "readline failed", e);
    inbuf = null;
    if(inbuf == null) {
    logger.fine("null received on: " + getAdd

    Here are three of them:
    NIO server
    NIO client
    Multithreaded server
    The stream based client example seems to have been deleted, probably lost in the troll wars. I also posted a new Simple multithreaded server that uses the same protocol. As the client is missing, I'll repost it.

  • Problem with socket connection through Java Embedding...

    We are trying to create a simple socket connection to a socket server through BPEL PM using the Java Embedding component.
    BPEL Process : Client makes an asynchronous request. Passes an input variable. The input variable is sent to the Server Program through a socket connection through the Java embedding component.
    Server: We are running a simple Socket Server program from command prompt.
    The code below works fine as long as we do not try to receive a response from the server (Commented Code).
    If we uncomment the code and try to receive a response, it refuses to create an instance for the BPEL Process. And sometimes restarts the BPEL Server.
    Client Code:
    String msg="NONE";
    try{
    org.w3c.dom.Element input = (org.w3c.dom.Element) getVariableData("inputVariable","payload","/client:clientProcessRequest/client:input");
    msg = input.getNodeValue();
    Socket clientsoc=new Socket("ServerIP",1000);
    PrintWriter out1=new PrintWriter(clientsoc.getOutputStream());
    out1.write(msg);
    out1.flush();
    BufferedReader cin1=new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
    msg=cin1.readLine();
    setVariableData("outputVariable","payload","/client:result",new String(msg));
    clientsoc.close();
    catch(UnknownHostException e)
    System.err.println("Don't know about host: dev.");
    System.exit(1);
    catch (IOException e)
    System.err.println("Couldn't get I/O for "+ "the connection to: dev.");
    System.exit(1);
    }

    Repost

Maybe you are looking for

  • White Screen

    I seem to be having a problem with my MacBook Pro and I was wondering if anyone could give me any suggestions. Earlier today I was watching a show on Hulu through Firefox, and then I opened Adium. After the buddy list loaded, I decided to close it ag

  • Use the Power Mac as a storage disk

    Hi I am setting up a iMac to be my main computer and was wondering if I could use my old Power Mac 4,1 as a storage disk? If so what would I need to do to have this happen?

  • My mac book pro will not start up

    when i try to turn on macbook pro the apple logo appears and the wheel turns but it will go any further, is there a solution for this

  • Users using Templates for SC creation

    Hi Is there a way in which users can only edit the quantity field when creating SC using public templates. In our case the users can edit all the fields of the templates created by buyers. Regards Ashish

  • Fireworks CS6 Freezes/crashes during launch

    It usually freezes on me when the launch graphic says it is "initializing keyboard shortcuts" Help!!