服务端:
服务器Server类
public class Server implements Runnable {
private int port;
private volatile boolean stop;
private Selector selector;
private ServerSocketChannel serverSocketChannel;
public Server(int port){
this.port = port;
}
public void init(){
try {
//打开一个选择器
selector = Selector.open();
//打开一个Server-Socket监听通道
serverSocketChannel = ServerSocketChannel.open();
//设置该通道为非阻塞模式
serverSocketChannel.configureBlocking(false);
//绑定端口
serverSocketChannel.socket().bind(new InetSocketAddress(port));
//将通道注册在选择器上面,并将准备连接状态作为通道订阅时间
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
stop = false;
System.out.println("服务器已经启动,端口号:" + port);
}catch (IOException e){
e.printStackTrace();
}
}
public void run() {
init();
while (!stop){
try {
//无论是否有读写事件发生,selector每隔1s被唤醒一次
selector.select(1000);
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
//判断是否准备好接收新进入的连接
if(selectionKey.isAcceptable()){
ServerSocketChannel serverSocketChannel = (ServerSock