我有这样的代码可以移植到 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);
}
}
我尝试过,但没有真正成功
es = Executors.newFixedThreadPool(2);
es.execute(new ListenTask());
和
public class ListenTask implements Runnable {
public void run() {
//Stream is a SocketChannel
_stream.socket().getInputStream().read(headerBuffer, 0, 1);
}
}
我应该使用 SocketChannel.read() 吗?
额外问题:java 中的等价物是什么 readOperation.AsyncWaitHandle.WaitOne();
非常感谢
最佳答案
Java 有 NIO,它支持非阻塞但不支持异步/事件驱动 IO。然而,在 NIO 之上构建了各种库来提供此类 API/行为。
最好的一个是 netty我可以根据个人使用情况推荐。
编辑:我相信真正的异步 IO 将在 Java 7 中出现。
关于c# - Java 相当于 C# Stream.BeginRead() 和 AsyncResult?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3542984/