前言
基于NIO实现多人模拟聊天窗口,首先要了解,NIO组件,ServerSocketChannel、SocketChannel、Selector、SelectorKey。了解了他们各自作用以及关系,多人聊天系统很容易理解实现,这里不在介绍,自行了解
服务器端
- 初始化服务端ServeSocketChannel 连接,绑定端口,并注册到Selector
- 通过Selectors 监听注册通道事件,根据事件进行用户上线、下线、消息读取、转发处理
public class ChatServer {
private ServerSocketChannel serverSocketChannel;
private static final int PORT = 9527;
private Selector selector;
/**
* 初始化
*
* @throws Exception
*/
public void initServer() throws Exception {
selector = Selector.open();
serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.register(selector, SelectionKey.OP_READ);
serverSocketChannel.configureBlocking(false);
}
/**
* 接受/转发客户端消息
*/
public void receiveClientInfo() throws Exception {
while (true) {
int select = selector.select();
if (select > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterators = selectionKeys.iterator();
while (iterators.hasNext()) {
//获取监听 key对象
SelectionKey key = iterators.next();
//有客户端连接
if (key.isAcceptable()) {
//获取socketChannel 客户端连接
SocketChannel socketChannel = serverSocketChannel.accept();
//设置非阻塞
socketChannel.configureBlocking(false);
//socketChannel 注册到selector 上
socketChannel.register(selector, SelectionKey.OP_ACCEPT);
//用户上线提醒
System.out.println("有用户上线:" + socketChannel.getRemoteAddress());
}
SocketChannel socketChannel = null;
try {
//读操作
if (key.isReadable()) {
socketChannel = (SocketChannel) key.channel();
//将数据从通道读取到缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int read = socketChannel.read(byteBuffer);
if (read > 0) {
String msg = new String(byteBuffer.array());
System.out.println("读取到数据:" + msg);
//转发消息给其它用户
tranceMessage2OtherClient(msg, socketChannel);
}
}
}catch (IOException e){
System.out.println("用户下线:"+socketChannel.getRemoteAddress());
key.cancel();
socketChannel.close();
}
//删除处理过的key
iterators.remove();
}
}
}
}
/**
* 转发消息到其他客户端
*
* @param msg
* @param selfChannel
*/
private void tranceMessage2OtherClient(String msg, SocketChannel selfChannel) throws Exception {
Set<SelectionKey> keys = selector.keys();
for (SelectionKey key : keys) {
Channel channel = key.channel();
//发送者不接受消息
if (channel instanceof SocketChannel && !channel.equals(selfChannel)) {
SocketChannel targetChannel = (SocketChannel) channel;
//消息写入到目标通道
int write = targetChannel.write(ByteBuffer.wrap(msg.getBytes()));
}
}
}
}
客户端
- 客户端初始化,并注册到selecotrs 上
- 发送消息到服务器
- 通过Selectors 监听通道读事件,读取消息
public class ChatClient {
private SocketChannel socketChannel;
private String host = "127.0.0.1";
private static final int PORT = 9527;
private Selector selector;
private String localFlag;
/**
* 初始客户端连接
*
* @throws Exception
*/
public void initClient() throws Exception {
socketChannel = SocketChannel.open(new InetSocketAddress(host, PORT));
socketChannel.configureBlocking(false);
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
localFlag = socketChannel.getLocalAddress().toString().substring(1);
System.out.println("客户端初始化完成..." + localFlag);
}
/**
* 发送消息
*
* @param msg
*/
public void sendMsg(String msg) {
msg += localFlag + "->" + msg;
try {
int write = socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 接受消息
*/
public void receiveMsg() {
try {
int channels = selector.select();
if (channels > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
if (selectionKey.isReadable()) {
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
channel.read(byteBuffer);
String readMsg = new String(byteBuffer.array());
System.out.println("读取消息:" + readMsg);
}
}
iterator.remove();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
总结
NIO 多人聊天实现,主要依靠NIO
Seletors
实现,Selectors
接受服务于客户端注册,并监听每个通道的事件,一旦有事件发生,即可进行处理。注册的事件即(Channel) 都会生成相应SelectKey
, 通过SelectKey
可以发现获取,有事件发生的通道。