共计 1026 个字符,预计需要花费 3 分钟才能阅读完成。
NIO 简易版聊天室
1. server 端:
package com.niewj.niochat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
/**
* Created by niewj on 2020/9/22 15:18
*/
public class NioChatServer {
public static final int PORT = 7777;
public static final int BUF_SIZE = 512;
private Selector selector;
private ServerSocketChannel serverChannel;
public static void main(String[] args) throws IOException {NioChatServer server = new NioChatServer();
server.init();
server.listen();}
private void listen() throws IOException {
// 关联胜利后 轮询监听客户端连贯
while (true) {
// 阻塞办法: 直到有注册的事件产生
int readyChannels = selector.select();
if (readyChannels == 0) {continue;}
// 收集监听的事件
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()) {SelectionKey key = iter.next();
if (key.isAcceptable()) {
// 解决 -accept 事件
handleAcceptable(key);
}
if (key.isReadable()) {
// 解决 -read 事件
readDataFromSocket(key);
}
/** 留神每次 iter.remove():
* Selector 不会本人移除 SelectionKey 实例, 必须在解决完 Channel 时本人移除。* 下次该通道就绪时,Selector 会再次将其放入已选择键集中。*/
正文完