我正在NetBeans(Java)中创建一个应用程序来打开套接字(客户端)并与之交换信息。
我这样做的方式如下:
final String HOST = "10.1.1.98";//"localhost";
final int PORT=1236;
Socket sc;
DataOutputStream message;
public void initClient()
{
try
{
sc = new Socket( HOST , PORT );
message = new DataOutputStream(sc.getOutputStream());
}
catch(Exception e )
{
System.out.println("Error: "+e.getMessage());
}
}
我必须知道服务器是否经常发送信息。一种方法是使用一个不断运行以下代码的计时器:
message = new DataOutputStream(sc.getOutputStream());
但效率不高。
我想创建一个事件来负责从服务器获取数据,例如在C#中我使用了EventHandler:
ip = new TcpIp(ipAddress, port);
ip.DataRead += new EventHandler<TramaEventArgs>(ip_DataRead);
....
void ip_DataRead(object sender, TramaEventArgs e)
{
}
我如何用Java做到这一点?
答案 0 :(得分:0)
在Java中执行非阻塞IO的“正确”方法是使用NIO API,特别是java.nio.channels.AsynchronousSocketChannel,它允许您编写如下代码:
InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName("10.1.1.98"), 1236);
AsynchronousSocketChannel clientSocketChannel = AsynchronousSocketChannel.open();
clientSocketChannel.connect(hostAddress).get();
ByteBuffer buffer = getBuffer();
clientSocketChannel.read(buffer, Void, new ReadHandler(buffer));
处理程序如下所示:
public class ReadHandler implements CompletionHandler<Integer, Void>
{
private ByteBuffer buffer;
public ReadHandler(ByteBuffer buffer)
{
this.buffer = buffer;
}
public void completed(Integer read, Void attachment)
{
if (read < 0)
{
return;
}
//TODO: read buffer according to the number of bytes read and process accordingly.
}
public void failed(Throwable exc, Void attachment)
{
//TODO: handle exception.
}
}
这里要注意的重要事项是:
ReadHandler
中尽可能少地处理,而不是将每个完整的消息传递出去(可能是ExecutorService
或某个内部队列,具体取决于您的要求。)