Adding Accepted Socket to Selector

OK,
I have gleaned the java.nio.channels.Selector et al.
I think I understand how to accept a socket. However, once I have; how do I add it to the Selector so that I can register for events on the new connected socket. Here is my source:
Set<SelectionKey> fdset = null;
Socket sock = null;
ServerSocket lstn = null;
selInst = Selector.open();
do
if( null==lstn )
ServerSocketChannel rChan = selInst.provider().openServerSocketChannel();
lstn = rChan.socket();
lstn.bind( new InetSocketAddress(2007) );
rChan.register( selInst, SelectionKey.OP_ACCEPT );
if( 0>selInst.select() )
continue;
fdset = selInst.selectedKeys();
for( SelectionKey key : fdset )
if( key.isAcceptable() )
ServerSocketChannel rCh0 = (ServerSocketChannel)key.channel();
sock = rCh0.socket().accept();
rCh0.register( selInst, SelectionKey.OP_READ )
//xx wait a minute -- ServerSocketChannel::socket() returns a ServerSocket,
//xx not a Socket class, don't I need a new SocketChannel? How do I
//xx attach my accepted socket?
} while( true );
See the comments above. The jist is there is no way to open() a new SocketChannel using an existing Socket class [returned by accept()], as far as I can tell.
Thanks,
James
Beverly, MA

I posted it as an official bug. Here is the tiny app I wrote to reproduce the problem:
* James A. Renton
* Beverly, MA
public class Main
    public Main()
    static void DoOtherWork( )
    {   //xx THIS function symbolizes other stuff
        //xx my thread could do as a result of using NIO
        //xx SUCH AS read and handle internal
        //xx process-specific message queue for
        //xx starting/stopping this thread
        //xx initiating work to be delegated
        //xx to the far end machine this thread communicates with.
        try{ Thread.sleep( 1000 );}catch( Throwable rEx ){/*NOOP*/};
    static ServerSocketChannel listen( Selector rSel, String zItfIP, int nPort )
        try
            ServerSocket sockLstn = null;
            ServerSocketChannel chanLstn = rSel.provider().openServerSocketChannel();
            chanLstn.configureBlocking(false);
            sockLstn = chanLstn.socket();
            sockLstn.bind( new InetSocketAddress(zItfIP,nPort) );
            chanLstn.register( rSel, SelectionKey.OP_ACCEPT );
            return chanLstn;
        catch( java.io.IOException rEx )
            System.out.printf( "accept SETUP FAILED, ERR=[%s]\n", rEx.toString() );
            return null;
    static SocketChannel connect( Selector rSel, String zTargetIP, int nPort )
        try
            SocketChannel chanOut = rSel.provider().openSocketChannel();
            chanOut.configureBlocking(false);
            if( chanOut.connect(new InetSocketAddress(zTargetIP,nPort)) )
                chanOut.register( rSel, SelectionKey.OP_READ );
            else
                chanOut.register( rSel, SelectionKey.OP_CONNECT );
            return chanOut;
        catch( java.io.IOException rEx )
            System.out.printf( "connect SETUP FAILED, ERR=[%s]\n", rEx.toString() );
            return null;
    static Selector GetSel( )
        try { return Selector.open(); }
        catch( java.io.IOException rEx )
            System.out.printf( "Selector.open() FAILED, ERR=[%s]\n", rEx.toString() );
            return null;
    static int DoSelect( Selector rSel, int millis )
        try { return rSel.select( millis ); }
        catch( java.io.IOException rEx )
            System.out.printf( "select() FAILED, ERR=[%s]\n", rEx.toString() );
            return -1;
    public static void main(String[] args)
        int nConnected = 0;
        java.util.Set<SelectionKey> fdset = null;
        System.out.printf( "java.version=[%s]\n", System.getProperty("java.version") );
        System.out.printf( "os.name=[%s]\n", System.getProperty("os.name") );
        System.out.printf( "os.version=[%s]\n", System.getProperty("os.version") );
        Selector selInst = GetSel();
        listen( selInst, "localhost", 2008 );
        connect( selInst, "localhost", 2008 );
        while( 0<=DoSelect(selInst,150) )
            fdset = selInst.selectedKeys();
            if( !fdset.isEmpty() )
                for( SelectionKey key : fdset )
                    try
                        if( key.isAcceptable() )
                            ServerSocketChannel chanLstn = (ServerSocketChannel)key.channel();
                            SocketChannel chanAccept = chanLstn.accept();
                            if( null==chanAccept )
                                System.out.println( "*** BUG0 : KEY FLAGGED ACCEPTING, NOTHING TO ACCEPT!" );
                            else
                                InetSocketAddress addr[] = new InetSocketAddress[2];
                                chanAccept.configureBlocking(false);
                                chanAccept.register( selInst, SelectionKey.OP_READ );
                                addr[0] = (InetSocketAddress)chanAccept.socket().getLocalSocketAddress();
                                addr[1] = (InetSocketAddress)chanAccept.socket().getRemoteSocketAddress();
                                System.out.printf( "ACCEPTED SOCK (%s)<-(%s) OK.\n",
                                                    addr[0].toString(), addr[1].toString() );
                        else if( key.isConnectable() )
                            SocketChannel rCh = (SocketChannel)key.channel();
                            Boolean bRC = rCh.finishConnect();
                            key.interestOps(SelectionKey.OP_READ);
                            if( 0!=nConnected++ )
                                System.out.printf( "*** BUG1 : KEY FLAGGED CONNECTING, ALREADY CONNECTED, RC=[%s]\n",
                                                    bRC.toString() );
                            else
                                InetSocketAddress addr[] = new InetSocketAddress[2];
                                addr[0] = (InetSocketAddress)rCh.socket().getLocalSocketAddress();
                                addr[1] = (InetSocketAddress)rCh.socket().getRemoteSocketAddress();
                                System.out.printf( "CONNECT SOCK (%s)->(%s) OK, RC=[%s]\n",
                                                    addr[0].toString(), addr[1].toString(), bRC.toString() );
                    catch( java.io.IOException rEx )
                        System.out.printf( "UnHandled IOException, ERR=[%s]", rEx.toString() );
                        rEx.printStackTrace();
            DoOtherWork();
}

Similar Messages

  • How close server socket without throwing exception to accepted socket

    Hi,
    In my project, we are closing the server by running a program which connects to server through socket.
    Through socket, it asks server to destroy all the process and atlast server exist it connection by
    System.exit(0);
    Because of this, accepted socket throws a socket exception which clients don't want to see in their log file.
    Is there any way to close the server in the accepted socket or to close without throwing exception.
    Thanks & Regards,
    Nasrin.N

    All you have to do is close the ServerSocket then wait for all currently executing accepted-socket threads to exit. Closing the ServerSocket won't do anything to accepted sockets, but terminating the process early via System.exit() will, and this is what you want to avoid.

  • ANOTHER Java NIO Socket Bug??

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

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

  • 100% cpu usage due to nio selector.open

    Hello guys,
    I am developing a multiplayer game using nio.In the begging i read all document related to nio.I have never heared about this api uses 100% cpu at server side as well as client side.
    When i start my server which is non blocking the cpu usage is dierctly raise to 100%.Working on Operating System windows 2000.Here is my code of server side.
    public void initializeOperations() throws IOException,UnknownHostException
              System.out.println("Inside initialization");
              sel = Selector.open(); //THIS FUNCTION RAISES CPU PERFORMANCE TO 100%....
              server = ServerSocketChannel.open();
              server.configureBlocking(false);
              InetAddress ia = InetAddress.getLocalHost();
              //InetSocketAddress isa = new InetSocketAddress(ia,port);
              InetSocketAddress isa = new InetSocketAddress(ia,port);
              server.socket().bind(isa);
         public void run() //startServer() throws Exception
              try
                   System.out.println("Inside startserver run()");
         initializeOperations();
                   SelectionKey acceptKey = server.register(sel, SelectionKey.OP_ACCEPT );
                   while (acceptKey.selector().select() > 0 )
              Set readyKeys = sel.selectedKeys();
              Iterator it = readyKeys.iterator();
              while (it.hasNext()) {
              SelectionKey key = (SelectionKey)it.next();
              it.remove();
              if (key.isAcceptable())
              System.out.println("Key is Acceptable");
    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
         socket = (SocketChannel) ssc.accept();
         socket.configureBlocking(false);
    SelectionKey another = socket.register(sel,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
              if (key.isReadable())
                                  System.out.println("Key is readable");
                                  String ret = readMessage(key);
                                  System.out.println("Frm clinet:"+ret);
                                  socket = (SocketChannel)key.channel();
              catch(Exception e)
                   System.out.println("Exception in ServerConnection:run()");
                   e.printStackTrace();
    Please see the code where i mentioned comment at that time cpu usage goes upto 100%.
    i searched the forum and find that OP_WRITE is creating problem but in my case even client is not comming than also server side cpu usage raises.
    please suggest proper solution
    thank you

    thank you for your suggestion...
    so u r telling to compile my application in new version of jdk and run from there..m i right???ok...
    i have tried this also in latest version jdk1.5.0_04 than also my cpu usage raise to 100%..
    Now i m trying using 1.4.2_08 hope it will work....
    is there any other idea to solve my problem please help me out...
    thank you

  • Socket disconnection event not being reveived java.nio

    Hi All
    My question is as below
    i am using java.nio package + win 2K + jdk1.4.1_02
    I have a Server accepting socket connection and is configured
    in Nonblocking mode.
    -The server receives (selector) events (accept event)
    when a client requests for a connection .
    -The server is getting read and write events when
    client wants to read and write
    -The server gets a read event when the client disconnects
    My only problem is that the Server is not getting any events
    when the client disconnect due to network break down
    for EX when the network connection breaks the client disconnects
    but the server selector is not getting any events
    I am storing the client Socket objects in a Hash Table and
    if i execute the .isConnected() method it returns true
    even though the the client is down
    The only work around is to try to read and write on the socket
    i get an IO exception and am able to make out that the
    client is disconnected
    But this is not desirable for my client
    as client modification to give any kind of echo is not possible and
    a read /write event will cause problem.
    Can any one tell how to detect client side disconnection
    with out Read and Write on the client socket
    I get an socket Exception when the socket is in Blocking IO and is blocked on read/ write but I am facing this problem in NonBlockingIO
    Regards
    Avinash

    int ct = read.selectNow();
    if (ct > 0)
    Set readyKeys = read.selectedKeys();
    Iterator i = readyKeys.iterator();
    while (i.hasNext())
    SelectionKey key = (SelectionKey) i.next();
    i.remove();
    if (key.isReadable())
    SelectableChannel nextReady = (SelectableChannel) key.channel();
    SocketChannel sc = (SocketChannel) key.channel();
    int rd = sc.read(buffer);
    // Link is dead
    if (rd == -1)
    key.cancel();
    key.attach(null);
    nextReady.close();
    continue;
    // Process your data
    catch (Exception e)
    e.printStackTrace();

  • Error when calling getLocalSocketAddress() on for a newly created socket

    Hello,
    I have an issue when using JVM 1.5.0.12 on HP-UX (IA64N):
    java.lang.Error: java.net.SocketException: Bad file number (errno:9)
         at sun.nio.ch.Net.localAddress(Net.java:123)
         at sun.nio.ch.SocketChannelImpl.localAddress(SocketChannelImpl.java:394)
         at sun.nio.ch.SocketAdaptor.getLocalAddress(SocketAdaptor.java:147)
         at java.net.Socket.getLocalSocketAddress(Socket.java:708)
    I get this error when I accept a connection from a remote peer and I try to call getLocalSocketAddress() method on the new accepted socket connection object.
    Does anyone have an idea about the cause for this error?
    I also get 2 other errors but in different places in the code:
    1/ java.io.IOException: No buffer space available (errno:233)
         at sun.nio.ch.ServerSocketChannelImpl.accept0(Native Method)
         at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:145)
    This one I get when my server socket accepts a connection. But even if the connection is accepted succesfully, I might get the "java.lang.Error: java.net.SocketException: Bad file number (errno:9)" when trying to call getLocalSocketAddress()
    2/ Once I accept the new connection I call "socketChannel.socket().setTcpNoDelay(true)" but sometimes this fails with a SocketException: Invalid argument (errno:22).
    Al the 3 errors are manifesting sporadically and I cannot find the cause.

    Hello,
    Thanks for your quick response!
    We actually do something like this:
    // NIO engine build around a Selector for asynchronous IO developpement.
    public class NIOCore implements Runnable {
    private final Selector selector;
    private final Set<SelectableChannelListener> channels = new HashSet<SelectableChannelListener>();
    public void run() {
    for (final Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();) {
    final SelectionKey selectionKey = i.next();
    i.remove();
    final SelectableChannelListener selectableChannelListener = (SelectableChannelListener) selectionKey.attachment();
    if (!selectionKey.isValid()) {
    continue;
    // Check what event is available and deal with it
    if (selectionKey.isAcceptable()) {
    if (log.isTraceEnabled()) {
    log.debug("Processing ACCEPT event for listener: " + selectableChannelListener);
    try {
    selectableChannelListener.acceptEvent();
    } catch (final Throwable t) {
    log.error("Error on ACCEPT event for listener " + selectableChannelListener, t);
    selectableChannelListener.close();
    As you ca see, we use to do a callback on our SelectableChannelListener objects. In our case the SelectableChannelListener object that actually propagates the JVM Error is this one:
    public final class Acceptor extends SelectableChannelListener {
    protected NIOCore core;
    public void acceptEvent() {
    SocketChannel socketChannel = serverSocketChannel.accept();
    if (socketChannel == null) {
    throw new NIOCoreException("No incoming connection to accept");
    // Socket options
    if (params.getSocketBufferSize() > 0) {
    socketChannel.socket().setSendBufferSize(params.getSocketBufferSize());
    try {
    socketChannel.socket().setTcpNoDelay(true);
    } catch (SocketException ex) {
    if (log.isDebugEnabled() || log.isTraceEnabled())
    log.warn(logPrefix + "could not set TCP_NODELAY socket option.You may experience performance loss", ex);
    else
    log.warn(logPrefix + "could not set TCP_NODELAY socket option. You may experience performance loss. Cause : " + ex.getMessage());
    // later if the connection is accepted succesfully this line is executed
    SocketAddress localAddress = socketChannel.socket().getLocalSocketAddress();
    @Override
    public void close() {
    core.unregister(this);
    try {
    selectableChannel.close();
    } catch (final IOException e) {
    // Ignore
    NIOPortManager.getInstance().setListenBindSapState(getBoundSAP(), true);
    So bassically when we call selectableChannelListener.close() we indeed close the ServerSocketChannel channel, but we also unregister the Acceptor observer object from NIOCore in order to free memory and set the SAP as available.
    The problem is that we cannot reproduce this issue (it reproduces only on our customers environment) and I consider rather risky to remove the selectableChannelListener.close() call.
    Actually I would catch the Error and package it in an internal runtime exception:
    SocketAddress localAddress = null;
    try {
    localAddress = socketChannel.socket().getLocalSocketAddress();
    catch (Throwable t) {
    throw new MyRunntimeException(t);
    And then to catch this new runtime exception in NIOCore class when this call is made:
    try {
    selectableChannelListener.acceptEvent();
    } catch (final MyRunntimeException e) {
    log.debug("JVM error occured!");
    } catch (final Throwable t) {
    log.error("Error on ACCEPT event for listener " + selectableChannelListener, t);
    selectableChannelListener.close();
    I know this is silly but at least we can use it as a temporary workaround until these JVM issues are fixed.
    Also since socketChannel.socket().getLocalSocketAddress() API call only throws that specific error from time to time, we could implement a retry mechanism. What I mean is to call getLocalSocketAddress() in a while loop and if the call fails with Error just continue to retry...we could provide 3 retries for example. If on the 3 ^rd^ retry the call also fails, just let it be failed and treat it in normal way.
    Best regards,
    Alex

  • Socket NIO Problems

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

    I'm not sure that a key will ever return with more than one operation bit selected. I expect that the selector simply puts the key into the selected set as soon as it sees any one of the interestedOps that match the current state.
    The general problem you are having, it seems, is that isWritable(), in many cases, will constantly return true for a low volume socket. This being the case, the only solution I see is to either deal with output with blocking calls or to dynamically change your interestedOps when there is data to write. That's what I did. I don't know yet how well it will scale. This is certainly not a bug, the application must deal with it. Perhaps it would be nice to have some kind of interface, like "SelectionKeyAttachment" and have the SelectionKey.attach() method take one of those. The SelectionKeyAttachment interface could implement something like isWritable(), isReadable(), isAcceptable() so that the Selector can also invoke the callback before putting it into the selected set. I haven't really thought this through, just initial thoughts.

  • Using sockets to relay video stream

    Hi there,
    I've been working with java for 4 years now, and I never had troubles making the applications I wanted with it...since my last project :(
    I hope you, gurus from the java community forum, can help me sort this out, but let me explain it to you:
    I'd like to stream video content (let's say from a webcam) to several spectators. But my upload bandwidth (ADSL line) is limited to 512kbps, which is far from enough to send a video streaming (with a bitrate of ~400kbps) to 10 or more viewers.
    That's why I decided to rent a distant server (with a bandwidth of 5Mbps download/upload), and make a java application run on it, which would be able to broadcast the stream to all the viewers.
    So my computer (connected to adsl) captures the video from the webcam, sends it via socket to the rented server, which broadcasts the video to all the spectators. If no video is sent to the rented server, then it should broadcast local files to the spectators.
    Here is a schema of the project so you understand easily (my english is not as good as I'd like it to be, so you may not understand with words only):
    http://www.bf-stream.com/schema1.gif
    My application runs quite well with 5 spectators, but as soon as more viewers come to see the video, it starts hanging, and all the viewers suffer lags and buffering, which is not exactly what I expected...
    Of course, I checked the administration interface on the rented server to see if this was due to a cpu/ram/bandwitdh problem. With no success: with 10 viewers connected, the app uses less than 1% of the cpu power, something like 200kb of RAM, and a bandwidth of 3-4Mbps (which is still under the actual bandwidth capacity of the server).
    That's why I came to the conclusion that my java app was not as good as I thought, and decided to show it to you, so you can help me make it better.
    So here is a schema showing the classes and their interactions:
    http://www.bf-stream.com/schema2.gif
    And here are the sources of the classes:
    StreamRelay.java:
    package com.RR4;
    import java.net.Socket;
    import java.util.Vector;
    import java.util.Observable;
    import java.util.Observer;
    * StreamRelay:
    *  Main class controlling every aspects of the stream
    *  (live content, or files read from hard disk)
    public class StreamRelay extends Observable implements Observer  {
         static public String VERSION = "0.5";
         static public int BUFFER_SIZE = 16;
         private StreamServer streamServer;
         private LiveServer liveServer;
         LocalFile localFile;
         Vector clients;
         boolean streamFromSocket;
         public StreamRelay(int livePort, int relayPort) {
              streamFromSocket = false;
              // clients: vector containing every StreamClient connected
              clients = new Vector();
              // localFile: class reading local files when no live is sent to the relay
              localFile = new LocalFile(this);
              new Thread(localFile).start();
              // streamServer: server listening for new StreamClient
              streamServer = new StreamServer(this, relayPort);
              new Thread(streamServer).start();
              // liveServer: server listening for new sources for live content
              liveServer = new LiveServer(this, livePort);
              new Thread(liveServer).start();
         * addClient: adds new StreamClient to 'clients' vector (a StreamClient is a 'spectator')
         public void addClient(Socket clientSocket) {
             StreamClient client = new StreamClient(this, clientSocket);
         * removeClient: removes a StreamClient from 'clients' vector
         public void removeClient(int index) {
              clients.remove(index);
         * update: updates every StreamClient (which are all Observers of StreamRelay)
         public void update(Observable observable, Object obj) {
              if ((observable.getClass().toString().indexOf("LocalFile")!=-1&&!streamFromSocket)||(observable.getClass().toString().indexOf("LiveStream")!=-1)) {
                   this.notifyObservers( (byte[]) obj);
                   this.setChanged();
         public static void main(String[] args) {
              new StreamRelay(8000, 8080);
    LocalFile.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    * LocalFile: class reading local file when no live content is sent to the relay
    public class LocalFile extends Observable implements Runnable {
         // filenames is an array containing a list of files to be read when no live content is sent
         private String[] filenames = {
              "file1",
              "file2"
         private InputStream stream;
         boolean streamOpened;
         private StreamRelay parent;
         int fileIndex;
         // Constructor: initialises LocalFile
         //  sets fileIndex to 0, and sets main StreamRelay as Observer
         public LocalFile(StreamRelay parent) {
              this.parent = parent;
              fileIndex = 0;
              this.addObserver(parent);
              initStream();
          * initStream: initialises stream to read the next file in 'filenames' array
         public void initStream() {
              try {
                   stream = new BufferedInputStream(new FileInputStream(filenames[fileIndex]), StreamRelay.BUFFER_SIZE);
                   streamOpened = true;
                   fileIndex++;
                   if (fileIndex==filenames.length)
                        fileIndex = 0;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
          * run: main loop of the class.
          *     the file is actually read: a buffer of BUFFER_SIZE is filled and sent to
          *     the observer (StreamRelay)
         public void run() {
              byte[] buffer = new byte[StreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              boolean quit = false;
              int actualBufferSize = 0;
              while (!quit) {
                   try {
                        this.setChanged();
                        // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                        // Only then is it sent to the observer...
                        while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, StreamRelay.BUFFER_SIZE)) > 0)) {
                             if (parent.clients.size()>0 && (!parent.streamFromSocket)) {
                                  if (actualBufferSize<StreamRelay.BUFFER_SIZE) {
                                       bufferToSend = new byte[actualBufferSize];
                                       System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                       this.notifyObservers(bufferToSend);
                                  } else
                                       this.notifyObservers(buffer);
                                  this.setChanged();
                             } else {
                                  try { Thread.sleep(100); } catch (Exception exp) {}
                   } catch (Exception exp) {
                        exp.printStackTrace();
                   try { stream.close(); } catch (Exception exp) {}
                   initStream();
    StreamServer.java:
    package com.RR4;
    import java.net.ServerSocket;
    public class StreamServer extends Thread {
         private ServerSocket serverSocket;
         private boolean socketOpened;
         private StreamRelay parent;
         * StreamServer: server listening for new StreamClient
         public StreamServer(StreamRelay parent, int relayPort) {
              this.parent = parent;
              try {
                   serverSocket = new ServerSocket(relayPort);
                   socketOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   socketOpened = false;
         public void run() {
              try {
                   while (socketOpened) {
                        parent.addClient(serverSocket.accept());
              } catch (Exception exp) {
                   exp.printStackTrace();
    StreamClient.java:
    package com.RR4;
    import java.net.Socket;
    import java.util.Observer;
    import java.util.Observable;
    import java.io.*;
    * StreamClient: class representing spectators connected to view the video content
    *     whether it is live content, or local files
    public class StreamClient implements Observer {
         private Socket socket;
         private OutputStream outStream;
         private boolean connected = true;
         private StreamRelay parent;
         public StreamClient(StreamRelay parent, Socket socket) {
              this.parent = parent;
              this.socket = socket;
              try {
                   // initialises OutputStream from socket
                   outStream = socket.getOutputStream();
              } catch (Exception exp) {
                   try { outStream.close(); } catch (Exception e) {}
                   try { socket.close(); } catch (Exception e) {}
                   exp.printStackTrace();
                   connected = false;
              if (connected) {
                   // if initializing of OutputStream didn't fail
                   // add this class to StreamBroadcast 'clients' vector
                   // and add this class to StreamRelay observers
                   parent.clients.add(this);
                   parent.addObserver(this);
          * update: actually send read bytes to the client
         public void update(Observable observable, Object obj) {
             try {
                   outStream.write( (byte[]) obj);
                   outStream.flush();
              } catch (Exception exp) {
                   // if read bytes couldn't be sent
                   // remove this client from clients list and observers of StreamRelay
                   // and try to close OutputStream and Socket
                   connected = false;
                   try { parent.deleteObserver(this); } catch (Exception e) {}
                   try { parent.clients.remove(this); } catch (Exception e) {}
                   try { outStream.close(); } catch (Exception e) {}
                   try { socket.close(); } catch (Exception e) {}
    LiveServer.java:
    package com.RR4;
    import java.net.ServerSocket;
    * LiveServer:
    *     SocketServer listening to new 'Live streams'
    public class LiveServer extends Thread {
         private ServerSocket liveSocket;
         private boolean liveServerOpened;
         private StreamRelay parent;
         public LiveServer(StreamRelay parent, int livePort) {
              this.parent = parent;
              try {
                   liveSocket = new ServerSocket(livePort);
                   liveServerOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   liveServerOpened = false;
         public void run() {
              LiveStream liveStream;
              try {
                   while (liveServerOpened) {
                        liveStream = new LiveStream(parent, liveSocket.accept());
                        new Thread(liveStream).start();
              } catch (Exception exp) {
                   exp.printStackTrace();
    LiveStream.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    import java.net.Socket;
    *     LiveStream:
    *          Socket receiving live content from another distant computer
    *          to display it instead of the local files.
    public class LiveStream extends Observable implements Runnable {
         private InputStream stream;
         boolean streamOpened;
         private StreamRelay parent;
         public LiveStream(StreamRelay parent, Socket socket) {
              this.parent = parent;
              this.addObserver(parent);
              try {
                   stream = new BufferedInputStream(socket.getInputStream(), StreamRelay.BUFFER_SIZE);
                   streamOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
         public void run() {
              byte[] buffer = new byte[StreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              int actualBufferSize = 0;
              try {
                   this.setChanged();
                   // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                   // Only then is it sent to the observer...
                   while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, StreamRelay.BUFFER_SIZE)) > 0)) {
                        if (!parent.streamFromSocket)
                             parent.streamFromSocket = true;
                        if (parent.clients.size() > 0) {
                             if (actualBufferSize<StreamRelay.BUFFER_SIZE) {
                                  bufferToSend = new byte[actualBufferSize];
                                  System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                  this.notifyObservers(bufferToSend);
                             } else
                                  this.notifyObservers(buffer);
                             this.setChanged();
                        } else
                             try { Thread.sleep(100); } catch (Exception exp) {}
              } catch (Exception exp) {
                   exp.printStackTrace();
              } finally {
                   try { stream.close(); } catch (Exception exp) {}
                   this.deleteObserver(parent);
                   parent.streamFromSocket = false;
    }For your information, I uses NSV/VP6 vbr as video codec (but this should have no incidence on it, since the app only takes the video stream from a socket and broadcasts it to other sockets, without analysing it or modifying it). And the java app is hosted on a Celeron 2.6 GHz, 128MB RAM.
    I really hope you'll be able to help me with this project, as it is really important to me...
    I've been trying several Stream types available with the JDK but I hadn't any success... I've also been playing with the BUFFER_SIZE parameter, unsuccessfully too...
    Anyway, thanks in advance for reading me so far... and I hope, for helping me... I know the java community is strong, and I hope I won't have to make it with C or C++ :(

    Hi again :)
    I've been focusing on the local part of the stream (no live video, just playing local files and sending them to clients) using NIO.
    NIOStreamRelay.java:
    package com.RR4;
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.net.*;
    import java.util.*;
    public class NIOStreamRelay {
         static int BUFFER_SIZE = 1024;
         LocalFile localFile;
         Vector clients;
         public NIOStreamRelay() throws IOException {
              localFile = new LocalFile(this);
              new Thread(localFile).start();
              clients = new Vector();
              acceptConnections();
         public void acceptConnections() throws IOException {          
              // Selector for incoming requests
              Selector acceptSelector = SelectorProvider.provider().openSelector();
              // Create a new server socket and set to non blocking mode
              ServerSocketChannel ssc = ServerSocketChannel.open();
              ssc.configureBlocking(false);
              // Bind the server socket to the local host and port
              InetAddress lh = InetAddress.getLocalHost();
              InetSocketAddress isa = new InetSocketAddress(lh, 8080);
              ssc.socket().bind(isa);
              // Register accepts on the server socket with the selector. This
              // step tells the selector that the socket wants to be put on the
              // ready list when accept operations occur, so allowing multiplexed
              // non-blocking I/O to take place.
              SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
              int keysAdded = 0;
              // Here's where everything happens. The select method will
              // return when any operations registered above have occurred, the
              // thread has been interrupted, etc.
              while ((keysAdded = acceptSelector.select()) > 0) {
                  // Someone is ready for I/O, get the ready keys
                  Set readyKeys = acceptSelector.selectedKeys();
                  Iterator i = readyKeys.iterator();
                  // Walk through the ready keys collection and process date requests.
                  while (i.hasNext()) {
                        SelectionKey sk = (SelectionKey)i.next();
                        i.remove();
                        // The key indexes into the selector so you
                        // can retrieve the socket that's ready for I/O
                        ServerSocketChannel nextReady = (ServerSocketChannel)sk.channel();
                        // Accept the date request and send back the date string
                        Socket s = nextReady.accept().socket();
                        OutputStream socketStream = s.getOutputStream();
                        StreamClient newClient = new StreamClient(socketStream, this);
                        localFile.addObserver(newClient);
                        clients.add(newClient);
         public static void main(String[] args) {
              try {
                   NIOStreamRelay streamRelay = new NIOStreamRelay();
              } catch (Exception e) {
                   e.printStackTrace();
    LocalFile.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    * LocalFile: class reading local file when no live content is sent to the relay
    public class LocalFile extends Observable implements Runnable {
         // filenames is an array containing a list of files to be read when no live content is sent
         private String[] filenames = {
              "test.nsv",
              "test2.nsv"
         private InputStream stream;
         boolean streamOpened;
         int fileIndex;
         NIOStreamRelay parent;
         // Constructor: initialises LocalFile
         //  sets fileIndex to 0, and sets main StreamRelay as Observer
         public LocalFile(NIOStreamRelay parent) {
              this.parent = parent;
              fileIndex = 0;
              initStream();
          * initStream: initialises stream to read the next file in 'filenames' array
         public void initStream() {
              try {
                   stream = new BufferedInputStream(new FileInputStream(filenames[fileIndex]), NIOStreamRelay.BUFFER_SIZE);
                   streamOpened = true;
                   fileIndex++;
                   if (fileIndex==filenames.length)
                        fileIndex = 0;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
          * run: main loop of the class.
          *     the file is actually read: a buffer of BUFFER_SIZE is filled and sent to
          *     the observer (StreamRelay)
         public void run() {
              byte[] buffer = new byte[NIOStreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              boolean quit = false;
              int actualBufferSize = 0;
              while (!quit) {
                   try {
                        this.setChanged();
                        // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                        // Only then is it sent to the observer...
                        while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, NIOStreamRelay.BUFFER_SIZE)) > 0)) {
                             if (parent.clients.size() > 0) {
                                  if (actualBufferSize<NIOStreamRelay.BUFFER_SIZE) {
                                       bufferToSend = new byte[actualBufferSize];
                                       System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                       this.notifyObservers(bufferToSend);
                                  } else
                                       this.notifyObservers(buffer);
                                  this.setChanged();
                             } else {
                                  try { Thread.sleep(100); } catch (Exception exp) {}
                   } catch (Exception exp) {
                        exp.printStackTrace();
                   try { stream.close(); } catch (Exception exp) {}
                   initStream();
    StreamClient.java:
    package com.RR4;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class StreamClient implements Observer {
         OutputStream out;
         NIOStreamRelay parent;
         public StreamClient(OutputStream out, NIOStreamRelay parent) {
              this.out = out;
              this.parent = parent;
         public void update(Observable observable, Object obj) {
             try {
                   out.write( (byte[]) obj);
                   out.flush();
              } catch (Exception exp) {
                   // if read bytes couldn't be sent
                   // remove this client from clients list and observers of StreamRelay
                   // and try to close OutputStream and Socket
                   try { parent.localFile.deleteObserver(this); } catch (Exception e) {}
                   try { parent.clients.remove(this); } catch (Exception e) {}
                   try { out.close(); } catch (Exception e) {}
    }Does it look better to you?
    I know I'm still using single threading, but as the IO should be non-blocking, I guess it should be better.
    Furthermore, I tried it locally, and was able to launch 30+ clients without buffering problems (huh, ok, my cpu here is only a 1.6GHz, so the display was a bit lagguy, but it didn't seem to buffer at all)

  • Selector

    I implemented a selector for multiplexing client sockets.
    Selector is responsible to listen to client connections and read from the client sockets. Accepting new connections and reading from client sockets are working fine. I was able to read data from client sockets and pass them to worker threads in the application. What is the model used to write to client sockets from worker threads in the application ?
    Below is the run() method for selector thread:
    while (true) {
    // Execute all the pending tasks.
    doInvocations();
    // Time to terminate?
    if (closeRequested) {
    return;
    int selectedKeys = 0;
    try {
    selectedKeys = selector.select();
    } catch (IOException ioe) {
    // Select should never throw an exception under normal
    // operation. If this happens, print the error and try to
    // continue working.
    ioe.printStackTrace();
    continue;
    if (selectedKeys == 0) {
    // Go back to the beginning of the loop
    continue;
    // Someone is ready for IO, get the ready keys
    Iterator it = selector.selectedKeys().iterator();
    // Walk through the collection of ready keys and dispatch
    // any active event.
    while (it.hasNext()) {
    SelectionKey sk = (SelectionKey)it.next();
    it.remove();
    try {
    // Obtain the interest of the key
    int readyOps = sk.readyOps();
    // Disable the interest for the operation that is ready.
    // This prevents the same event from being raised multiple
    // times.
    sk.interestOps(sk.interestOps() & ~readyOps);
    SelectorHandler handler =
    (SelectorHandler) sk.attachment();
    // Some of the operations set in the selection key
    // might no longer be valid when the handler is executed.
    // So handlers should take precautions against this
    // possibility.
    // Check what are the interests that are active and
    // dispatch the event to the appropriate method.
    if (sk.isAcceptable()) {
    // A connection is ready to be completed
    ((AcceptSelectorHandler)handler).handleAccept();
    } else if (sk.isConnectable()) {
    // A connection is ready to be accepted
    ((ConnectorSelectorHandler)handler).handleConnect();
    } else {
         ReadWriteSelectorHandler rwHandler =
              (ReadWriteSelectorHandler)handler;
         // Readable or writable
         if (sk.isReadable()) {
              // It is possible to read
              rwHandler.handleRead();
         // Check if the key is still valid, since it might
         // have been invalidated in the read handler
         // (for instance, the socket might have been closed)
         if (sk.isValid() && sk.isWritable()) {
              // It is read to write
              rwHandler.handleWrite();
    } catch (Throwable t) {
    // No exceptions should be thrown in the previous block!
    // So kill everything if one is detected.
    // Makes debugging easier.
    closeSelectorAndChannels();
    t.printStackTrace();
    return;
    }     // While iterator
    }     // Main while

    hmm... the new list element seems to work, i'm going to try that, but is there a way to validate on it?

  • Need help with java.nio.socket program.

    Can someone please help me here? I am trying to create a class that listens on a socket for an incoming connection, but I am getting the following error on compile:
    SocketIn.java:48: incompatible types
    found : java.nio.channels.SocketChannel
    required: java.net.Socket
    Socket requestSocket = requestChannel.accept();
    Here is my code:
    package NETC;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    public class SocketIn{
         // Buffer for any incoming data.
         private static ByteBuffer inBuffer = ByteBuffer.allocateDirect(1024);
         CharBuffer charBuffer = null;
         public SocketIn(int intPort)throws Exception{
              // Create a non-blocking server socket.
              ServerSocketChannel serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking(false);
              // Use the host and port to bind the server socket.
              InetAddress inetAddress = InetAddress.getLocalHost();
              InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, intPort);
              serverChannel.socket().bind(socketAddress);
              // The selector for incoming requests.
              Selector requestSelector = SelectorProvider.provider().openSelector();
              // Put the server socket on the selectors 'ready list'.
              serverChannel.register(requestSelector, SelectionKey.OP_ACCEPT);
              while(requestSelector.select() > 0){
                   System.out.println("Connection Accepted...");
                   // A request has been made and is ready for IO.
                   Set requestKeys = requestSelector.selectedKeys();
                   Iterator iterator = requestKeys.iterator();
                   while(iterator.hasNext()){
                        SelectionKey requestKey = (SelectionKey)iterator.next();
                        // Get the socket that's ready for IO.
                        ServerSocketChannel requestChannel = (ServerSocketChannel)requestKey.channel();
                        // This shouldn't block.
                        Socket requestSocket = requestChannel.accept();
                        inBuffer.clear();
                        requestSocket.read(inBuffer);                    
                        inBuffer.flip();
                        Charset charset = Charset.forName("ISO-8859-1");
                        CharsetDecoder decoder = charset.newDecoder();
                        charBuffer = decoder.decode(inBuffer);
                        iterator.remove();                    
    }

    Well its been about a month and a half so I guess you have your answer. In case you don't...
    // This shouldn't block.
    Socket requestSocket = requestChannel.accept();
    The problem is quite simple. The ServerSocketChannel.accept() returns a SocketChannel. (Channel -> Channel).
    You can get access to the socket using the SocketChannel.
    SocketChannel requestSocketChannel = requestChannel.accept();
    Socket requestSocket = requestSocketChannel.socket();
    But you don't need the socket to read and write.

  • Trouble connecting sockets...

    hi.
    i'm trying to connect to sockets over the internet but everytime i used my computers domain name when setting up the socket on the clients side they do not connect , here is the code im using:
    server
    ServerSocket serversocket = null;
    Socket clientsocket = null;
    try {
    serversocket = new ServerSocket(4444);
    clientsocket.accept();
    catch (Exception e) { }
    client
    Socket clientsocket = null;
    try {
    clientsocket = new Socket("mydomain", 4444);
    catch (Exception e) { }
    I'm testing these using the same computer and the only way it will connect is if i use my computers name which is "Craig" as the domain name but when i tested it on two computers it never worked
    ???

    here is my full source codes for my server and client progs:
    client:
    import java.net.*;
    import java.io.*;
    public class client {
    public static void main(String[] ags) {
    Socket clientsocket = null;
    try {
    clientsocket = new Socket(InetAddress.getByName(""), 6795);
    System.out.println("Connected");
    catch (Exception e) {
    System.out.println("error occured: " + e);
    server
    import java.net.*;
    import java.io.*;
    public class server {
    public static void main(String[] args) {
    ServerSocket serversocket = null;
    Socket clientsocket = null;
    try {
    serversocket = new ServerSocket(6795);
    System.out.println("Adding new socket to port 6795");
    System.out.println("waiting for client...");
    clientsocket = serversocket.accept();
    System.out.println("connected");
    catch (Exception e) {
    System.out.println("error occured: " + e);
    ???

  • Selector, SelectionKey, Iterator, Set, ... in NIO

    Any body explain for what need the Selector, SelectionKey, Iterator, Set, ... ( if possible on examples )
    I wrote simple code used NIO that send a canned text, but I can't advancing.
    Thanks,
    ~Leeloo

    I rewrote one of examples in J2SDK1.4.0 docs, NBTimeServer, here are snippet:
    Now, I want it to read requests and send responses. How can I do it?
    Selector acceptSelector = Selector.open();
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), PORT);
    ssc.socket().bind(isa);
    SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
    int keysAdded = 0;
    while ((keysAdded = acceptSelector.select()) > 0) {
    Set readyKeys = acceptSelector.selectedKeys();
    Iterator i = readyKeys.iterator();
    while (i.hasNext()) {
    SelectionKey sk = (SelectionKey)i.next();
    i.remove();
    if (sk.isAcceptable()) {
    ServerSocketChannel nextReady = (ServerSocketChannel)sk.channel();
    Socket s = nextReady.accept().socket();
    PrintWriter out = new PrintWriter(s.getOutputStream(), true);
    String str = "Welcome to NIO!!!";
    out.println(str);
    out.close();

  • File not found after socket transfer

    I have code written to upload a file to the server. the file uploads fine when i dont specify the dir. It uploads to the server current dir, but when i try to upload it to directory "tmp/uniqueDir/filename" that i create in my code i get filnotfound exception. can someone please help me figure out why?
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    public class ServerUtil {
         String tmpDir;
         String fileName;
         Process proc;
         Runtime runtime = Runtime.getRuntime();
         public static final int BUFFER_SIZE = 1024 * 50;
         private byte[] buffer;
         public ServerUtil() {
              // TODO Auto-generated constructor stub
         public void generateTmpDir(){
              java.util.Date d = new java.util.Date();
              long off = (long) Math.random();
              GregorianCalendar todaysDate=new GregorianCalendar();
              int hour,mins,secs;
              hour=todaysDate.get(Calendar.HOUR);
              mins = todaysDate.get(Calendar.MINUTE);
              secs = todaysDate.get(Calendar.SECOND);
              String SECS = java.lang.Integer.toString(secs);
              String HOUR = java.lang.Integer.toString(hour);
              String MINS = java.lang.Integer.toString(mins);
              String time = HOUR + MINS + SECS;
              /** Unique String Name **/
              String RANDOM_OFFSET = new String ();
              RANDOM_OFFSET =time + d.hashCode() + RANDOM_OFFSET.hashCode()+ off;
              setTmpDir(RANDOM_OFFSET);
              try {
                   proc = runtime.exec("mkdir tmp/" + getTmpDir() );
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public void uploadFile(Socket socket, BufferedReader rd){
              buffer = new byte[BUFFER_SIZE];
              System.out.println("accepted Socket");
              try {
              BufferedInputStream in =
                   new BufferedInputStream(socket.getInputStream());
              setFileName(rd.readLine());
              System.out.println(fileName);
              BufferedOutputStream out =
                   new BufferedOutputStream(new FileOutputStream("tmp/" + getTmpDir() +"/" + getFileName()));
              int len = 0;
              while ((len = in.read(buffer)) > 0) {
                   out.write(buffer, 0, len);
                   System.out.print("#");
              in.close();
              out.flush();
              out.close();
              socket.close();
              System.out.println("\nDone!");
              catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
          * @return the tmpDir
         public String getTmpDir() {
              return tmpDir;
          * @param tmpDir the tmpDir to set
         public void setTmpDir(String tmpDir) {
              this.tmpDir = tmpDir;
          * @return the fileName
         public String getFileName() {
              return fileName;
          * @param fileName the fileName to set
         public void setFileName(String fileName) {
              this.fileName = fileName;
    }this is the error im getting:
    java.io.FileNotFoundException: tmp/0859124333356700/fileName (A file or directory in the path name does not exist.)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:201)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:153)
    at EpkgArchiveServerUtil.uploadFile(ServerUtil.java:93)
    at ServerThreads.run(ServerThreads.java:38)

    You mean this code?proc = runtime.exec("mkdir tmp/" + getTmpDir() );Does it run with the same working directory as your Java code? And why don't you wait until it finishes? And more to the point, why don't you just use the java.io.File method that will make a directory for you instead of doing a clumsy thing like that?

  • How can i reuse my existing socket connection

    Hi,
    this might sound basic, it probably is:
    As part of my larger project, i have to send and recieve data to multiple socket connections.
    The thing that happens is that everytime i send data, it seems that java is creating a new stream or something (code is multithreaded)
    so as i send 4 items of data, a bit like a chat program sending 4 statements, it creates 4 different streams, instead of using the same stream. therefore when i close the connection, i get:
    java.net.SocketException: Connection reset 4 times.
    i know why.. its because i have added the:
    Socket socket=new Socket(host, port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    bit in the same method with the
    out.println(THE DATA....);
    out.flush();
    The thing what i want to do is to create the connection one, and reuse the objects:
    out, in and socket
    to send / recieve the new data.
    please help me guys,
    thanks

    All the threads would be able to get the same reference to....
    class SocketWrapper {
         private final Object readLock = new Object();
         private final Object writeLock = new Object();
         // client side
        public SocketWrapper(String hostname, int port);
         // server side.
        public SocketWrapper(Socket);
         // send data
         public void send(Serializable object) throws IOException;
         // receive data. synchronized(writeLock);
         public Serializable getNext() throws IOException;
         // create a new socket as required, throw IllegalState if server side. synchronized(readLock)
         private void createNewSocket() throws IllegalStateException;
    }The send autoconnects as required. It then send on message/packet/object.
    The getNext autoconnects as required. It reads one message/packet/object and returns.
    This allows multiple threads to access the same socket. It allows data to be sent while a thread is blocking on a read. (Thus two locks)

  • View Selector - Switch issue between Graph and Table Data

    Hi:
    We have created the report with both Table view and Chart View. Both of them has been added to the View Selector and added to the Dashboard. While performing the testing we found that sometimes the Switch between the views are not happening. Meaning when we try to switch from Chart View to Table View, the View changes in the drop down but the original Graph to table will not switch. In order to make that happen we need to try 3 or 4 times across the drop downs from Table to Chart and then chart to table.
    Did any one face the similar issue. Any suggestions or insights on this.
    Please help.
    Thanks & Regards
    Sunil Kumar T.S.

    hey there RAM,
    here are a few tips...
    1. what is the table field with the right value? and is this table field in the *itm extractor?
    2. can you include this field into the extractor?
    3. could it be a calculated value?
    hope this helps.

Maybe you are looking for