我正在 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 中做到这一点?
最佳答案
在 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
或某些内部队列,具体取决于您的要求)。
关于java - 如何在Java(TelNet)中实现接收套接字的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21434392/