简体   繁体   English

Java NIO-在服务器端注销客户端连接

[英]Java NIO - deregister client connection on server side

I am writing a simple NIO server using Selectors and NIO channels. 我正在使用Selectors和NIO通道编写一个简单的NIO服务器。 Every time I have an incoming connection, I register it with the Selector using the following code: 每次有传入连接时,我都会使用以下代码在选择器中注册它:

// accept connection
 SocketChannel client = server.accept();
 System.out.println("Accepting connection from " + client.socket().getLocalSocketAddress());

 client.configureBlocking(false);
 client.socket().setTcpNoDelay(true);
 client.register(selector, SelectionKey.OP_READ);

On the client side, since I have only one socketChannel, it is easy to simply close the channel and de-register with the selector. 在客户端,由于我只有一个socketChannel,因此很容易简单地关闭通道并向选择器注销。 On the erver side, however, all I'm doing is await writes from ANY client that ever connected (potentially thousands). 然而,从另一方面说,我正在做的就是等待任何曾经连接过的客户端(可能数千个)的写入。 I sthere a way to detect that the client has disconnected on the server side? 我使用了一种方法来检测客户端在服务器端已断开连接? It seems that the selector will get very inefficient after eg 10K connections, most of which would probably be dead after a short while.. 似乎选择器在经过10K个连接后会变得非常低效,其中大部分可能会在不久后消失。

When the client disconnects, the server will get an OP_READ event for the channel, and read() will return -1. 当客户端断开连接时,服务器将获得该通道的OP_READ事件,而read()将返回-1。 When this happens, close the channel. 发生这种情况时,请关闭通道。

NB You only have to close the channel. 注意您只需要关闭频道。 Cancelling the key, deregistration etc, happens automatically. 取消密钥,注销等会自动发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM