tags:

views:

84

answers:

3

Hi,

I've got this kind of code to port to Java:

public class MyClass
{
    Stream _stream;
    AsyncCallback callback;
    IAsyncResult readOperation;

    public MyClass(string host, string port)
    {
        TcpClient tcpClient = new TcpClient();
        tcpClient.Connect(host, port);
        _stream = tcpClient.GetStream();
        callback = new AsyncCallback(Read);
        readOp = _stream.BeginRead(headerBuffer, 0, 1, callback, null);
    }

    private void listen(IAsyncResult asyncResult)
    {
        _stream.EndRead(asyncResult);
        //Do some work
        readOperation = _stream.BeginRead(headerBuffer, 0, 1, callback, null);
    }
}

I've tried this with no real success

es = Executors.newFixedThreadPool(2);
es.execute(new ListenTask());

and

public class ListenTask implements Runnable {

    public void run() {
        //Stream is a SocketChannel
    _stream.socket().getInputStream().read(headerBuffer, 0, 1);
    }
}

Should I use SocketChannel.read() ?

Bonus question : What would be the java equivalent of readOperation.AsyncWaitHandle.WaitOne();

Thank you very much

A: 

I don't think there's a direct language equivalent built into the JDK, but it's possible to cobble together one of your own:

http://onjava.com/pub/a/onjava/2003/05/21/delegates.html

If not, then perhaps Java NIO - non-blocking I/O - is what you're looking for.

duffymo
I've already dealt with some delegates in the application but I was thinking this problem was more related to async IO programming.
SuperAllumette
A: 

AFAIK Java core doesn't have asynchronous i/o that you are looking for, but it doesn't seem to be a big problem to make one yourself - create a couple of classes which implement a thread (one for reading, one for writing), make contstructors of those classes accept the same parameters as BeginRead/BeginWrite, add delegates and that's all. The article on delegates can be found in the answer above.

Eugene Mayevski 'EldoS Corp
Java NIO is all about non-blocking I/O.
duffymo
I stand corrected.
Eugene Mayevski 'EldoS Corp
A: 

Java has NIO which supports non-blocking but not asychronous/event driven IO. However various libraries have been built on top of NIO that offer this sort of API/behaviour.

One of the best one is netty which I can recommend from personal use.

EDIT: I believe true async IO is coming in Java 7.

Mike Q
Yes, netty and mina looks fine. And I need SSL support, which both of them got. Thanks :)
SuperAllumette