NIO群聊系统demo示例
基本框架:

一、服务端
服务端代码
package nio.groupchat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class MyServer {
//定义属性
private Selector selector;
//做监听的
private ServerSocketChannel listenChannel;
public static final int Port = 6667;
//构造器
//初始化
public MyServer(){
try{
//得到选择器
selector = Selector.open();
//
listenChannel = ServerSocketChannel.open();
//bind port
listenChannel.socket().bind(new InetSocketAddress(Port));
//set 非阻塞
listenChannel.configureBlocking(false);
//将listener注册到selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
}catch(IOException e){
e.printStackTrace();
}
}
public void listen(){
try {
//循环
while(true){
int count = selector.select(2000);
if(count>0){
//event come
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
//取出selectorkey
SelectionKey key = iterator.next();
//listened accept
if(key.isAcceptable()){
SocketChannel socketChannel = listenChannel.accept();
//将该sc注册到select上面
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.

最低0.47元/天 解锁文章
863

被折叠的 条评论
为什么被折叠?



