代码
基于之前说的,做一个nio的群聊系统。代码如下:
服务器端:
package com.anxin.groupchat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
public class GroupChatServer {
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 8888; // 端口号
// 初始化
public GroupChatServer(){
try {
selector = Selector.open();
listenChannel = ServerSocketChannel.open();
// 绑定端口
listenChannel.socket().bind(new InetSocketAddress(PORT));
// 设置为非阻塞
listenChannel.configureBlocking(false);
// 注册
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
//监听
public void listen() {
System.out.println("监听线程: " + Thread.currentThread().getName());
while (true){
try {
int select = selector.select();
if(select > 0){
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey next = iterator.next();
if(next.isAcceptable()){
SocketChannel accept = listenChannel.accept();
accept.configureBlocking(false);
accept.register(selector,SelectionKey.OP_READ);
System.out.println(accept.getRemoteAddress() + " 上线 ");
}
if (next.isReadable()){
readData(next);
}
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void readData(SelectionKey key) {
//取到关联的channle
SocketChannel channel = null;
try {
channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int read = channel.read(byteBuffer);
if (read > 0) {
String buffer = new String(byteBuffer.array());
System.out.println(buffer);
// 转发
forword(buffer, channel);
}
} catch (Exception e) {
try {
System.out.println(channel.getRemoteAddress() + " 离线了..");
//取消注册
key.cancel();
//关闭通道
channel.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
private void forword(String buffer, SocketChannel channel) {
System.out.println("服务器转发消息中...");
System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
Set<SelectionKey> keys = selector.keys();
for (SelectionKey key : keys) {
Channel channel1 = key.channel();
if(channel1 instanceof SocketChannel && channel1 != channel){
SocketChannel channel2 = (SocketChannel) channel1;
try {
channel2.write(ByteBuffer.wrap(buffer.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//创建服务器对象
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}
客户端如下
package com.anxin.groupchat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class GroupChatClient {
//定义相关的属性
private final String HOST = "127.0.0.1"; // 服务器的ip
private final int PORT = 8888; //服务器端口
private final Selector selector;
private SocketChannel socketChannel;
private final String username;
//构造器, 完成初始化工作
public GroupChatClient() throws IOException {
selector = Selector.open();
//连接服务器
socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
//设置非阻塞
socketChannel.configureBlocking(false);
//将channel 注册到selector
socketChannel.register(selector, SelectionKey.OP_READ);
//得到username
username = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(username + " is ok...");
}
public static void main(String[] args) throws Exception {
//启动我们客户端
GroupChatClient chatClient = new GroupChatClient();
//启动一个线程, 每个3秒,读取从服务器发送数据
new Thread() {
public void run() {
while (true) {
chatClient.readMsg();
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
//发送数据给服务器端
String s = "服务器,听我说谢谢你";
chatClient.sendMsg(s);
}
public void sendMsg(String msg) {
msg = username + ":" + msg;
try {
socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void readMsg() {
int select = 0;
try {
select = selector.select();
if (select > 0) {
Iterator<SelectionKey> iterator = selector.keys().iterator();
while (iterator.hasNext()) {
SelectionKey next = iterator.next();
if (next.isReadable()) {
SocketChannel channel = (SocketChannel) next.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
channel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
}
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
原理图
实现通过一个阻塞对象监听所有请求
Reactor通过Selector监听,然后通过Dispatcher进行分发
如果建立请求连接事件,那么先用一个Acceptor连接,好了之后再用Handler进行处理
如果并不是请求连接事件,Reactor会调用Handler去处理
Handler的流程:read -> hander -> send 的过程
优缺点分析
优点:简单,一个线程之内全部搞定
缺点:也是只有一个线程,无法充分的利用多核CPU,很容易到达瓶颈。也不可靠,如果出了什么问题,就不能够再接受和处理事件了。而且一个线程也不能面对大量请求短时间之内处理。
场景:客户端有限,可以快速处理