4.3 处理 accept 事件

简介: 4.3 处理 accept 事件

public class Client { public static void main(String[] args) { try (Socket socket = new Socket("localhost", 8080)) { System.out.println(socket); socket.getOutputStream().write("world".getBytes()); System.in.read(); } catch (IOException e) { e.printStackTrace(); } } }

服务器端代码为

@Slf4j public class ChannelDemo6 { public static void main(String[] args) { try (ServerSocketChannel channel = ServerSocketChannel.open()) { channel.bind(new InetSocketAddress(8080)); System.out.println(channel); Selector selector = Selector.open(); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_ACCEPT);


        while (true) {
            int count = selector.select();

//                int count = selector.selectNow(); log.debug("select count: {}", count); //                if(count <= 0) { //                    continue; //                }

            // 获取所有事件
            Set<SelectionKey> keys = selector.selectedKeys();
            // 遍历所有事件,逐一处理
            Iterator<SelectionKey> iter = keys.iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                // 判断事件类型
                if (key.isAcceptable()) {
                    ServerSocketChannel c = (ServerSocketChannel) key.channel();
                    // 必须处理
                    SocketChannel sc = c.accept();
                    log.debug("{}", sc);
                }
                // 处理完毕,必须将事件移除
                iter.remove();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

💡 事件发生后能否不处理

事件发生后,要么处理,要么取消(cancel),不能什么都不做,否则下次该事件仍会触发,这是因为 nio 底层使用的是水平触发

目录
相关文章
|
6天前
v-on能否监听多个事件?
v-on能否监听多个事件?
|
6天前
socket编程之 accept函数的理解
在进入我们的正题之前,再来复习一波编写服务器的函数流程吧
66 0
|
7月前
|
网络协议
Tcp Accept返回的Socket不能作为唯一标示
Tcp Accept返回的Socket不能作为唯一标示
|
9月前
|
监控 前端开发
服务器发送事件(Server-Sent Events)
服务端向客户端推送消息,其实除了可以用WebSocket这种耳熟能详的机制外,还有一种服务器发送事件(Server-Sent Events),简称 SSE。这是一种服务器端到客户端(浏览器)的单向消息推送。
334 0
|
数据库
为socket的recv/send设置超时
为socket的recv/send设置超时
231 0
stream_socket_accept设置非阻塞,socket_accept设置非阻塞
stream_socket_accept设置非阻塞,socket_accept设置非阻塞
161 0