遍历selector里面的keys时候要注意区别ServerSocketChannel和SocketChannel

昨天学习nio实现 上线提醒 功能时候,粗心导致bug,记录一下

功能主要是实现 在一个客户端上线时候,服务器会给其他客户端推送上线信息

/**
     * 上线提醒
     */
    private void onlineReminder(SelectionKey key) throws IOException {
        Iterator<SelectionKey> iterator = selector.keys().iterator();
        SelectableChannel c = key.channel();
        while (iterator.hasNext()) {
            SocketChannel channel = (SocketChannel) iterator.next().channel();//这里把所有遍历出来的key.channel都统一强转为SocketChannel
            if (c != channel)
                channel.write(ByteBuffer.wrap((c.getRemoteAddress() + "上线了。").getBytes()));
        }
    }

上面bug主要在于:没有考虑到遍历出来的key是包含ServerSocketChannel的。强转为 SocketChannel 并进行写入会导致连接中断,出现java.io.IOException: 远程主机强迫关闭了一个现有的连接。

正确的处理办法是:在强转之前加一个检验,判断其是否是SocketChannel

/**
     * 上线提醒
     */
    private void onlineReminder(SelectionKey key) throws IOException {
        SelectableChannel c = key.channel();//当前上线的channel
        for (SelectionKey selectionKey : selector.keys()) {
            SelectableChannel channel = selectionKey.channel();
            if ((c != channel) && (channel instanceof SocketChannel)) {
                ((SocketChannel) channel).write(ByteBuffer.wrap((((SocketChannel) c).getRemoteAddress() + " 上线了。").getBytes()));
            }
        }
        /*for (SelectionKey key : selector.keys()) {
            SelectableChannel channel = key.channel();
            if (channel instanceof SocketChannel && channel != self) {
                SocketChannel socketChannel = (SocketChannel) channel;
                try {
                    socketChannel.write(ByteBuffer.wrap((self.getRemoteAddress() + " 上线了。").getBytes()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用`SocketChannel`结合`Selector`和`ThreadPool`来实现服务端。下面是一个简单的示例代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Server { private Selector selector; private ServerSocketChannel serverSocketChannel; private ExecutorService executorService; private static final int BUFFER_SIZE = 1024; public static void main(String[] args) throws IOException { Server server = new Server(); server.start(8080); } public void start(int port) throws IOException { // 创建Selector selector = Selector.open(); // 创建ServerSocketChannel并绑定端口 serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(port)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 创建线程池 executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // 事件循环 while (true) { // 阻塞等待就绪的事件 selector.select(); // 获取就绪的SelectionKey集合 Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); // 处理事件 if (key.isAcceptable()) { handleAcceptable(key); } else if (key.isReadable()) { handleReadable(key); } } } } private void handleAcceptable(SelectionKey key) throws IOException { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel clientChannel = serverChannel.accept(); clientChannel.configureBlocking(false); clientChannel.register(selector, SelectionKey.OP_READ); System.out.println("New client connected: " + clientChannel.getRemoteAddress()); } private void handleReadable(SelectionKey key) { SocketChannel clientChannel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); try { int bytesRead = clientChannel.read(buffer); if (bytesRead > 0) { buffer.flip(); byte[] data = new byte[buffer.remaining()]; buffer.get(data); String message = new String(data).trim(); System.out.println("Received message from client: " + message); // 在线程池中处理业务逻辑 executorService.execute(() -> { // 业务逻辑处理代码 // ... // 响应客户端 ByteBuffer responseBuffer = ByteBuffer.wrap("Response from server".getBytes()); try { clientChannel.write(responseBuffer); } catch (IOException e) { e.printStackTrace(); } }); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例代码创建了一个基于`SocketChannel`的服务端,使用`Selector`来实现异步的事件处理,使用`ThreadPoolExecutor`来处理业务逻辑。客户端连接的接收和读取操作在`handleAcceptable`和`handleReadable`方法中处理。读取到客户端消息后,会将业务逻辑交给线程池处理,并响应客户端。你可以根据自己的需要在业务逻辑处理代码中添加具体的业务逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值