1

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

  • And the `m` tag is for......? – skaffman Aug 22 '10 at 19:26
  • That was a mistyping, my bad. – SuperAllumette Aug 22 '10 at 19:27
  • NetworkStream.BeginRead doesn't just run Read in a different thread. It delegates reading to the operating system, which will call back into the C# code when data has been received ("IO completion ports"). Java apparently doesn't have an equivalent (yet); see http://stackoverflow.com/questions/592303 – dtb Aug 22 '10 at 19:39
  • I will try one of the listed framework then. Thanks for your answers – SuperAllumette Aug 22 '10 at 19:48

3 Answers3

1

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
  • 22,839
  • 20
  • 87
  • 129
0

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
  • 305,152
  • 44
  • 369
  • 561
  • I've already dealt with some delegates in the application but I was thinking this problem was more related to async IO programming. – SuperAllumette Aug 22 '10 at 19:37
0

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 'Callback
  • 45,135
  • 8
  • 71
  • 121