一、非阻塞网络编程
NIO 非阻塞网络编程中Selector、SelectionKey、 ServerSocketChannel和SocketChannel的关系:
图解:
①一个线程对应一个 Selector
②客户端连接时,服务端通过 ServerSocketChannel 得到一个和客户端对应的 SocketChannel,并将该 SocketChannel 注册到 Selector 得到一个 SelectionKey (在服务端 SelectionKey 是 SocketChannel 的标识,通过SelectionKey的channel()方法能够反向获取到SocketChannel,获取到SocketChannle后就可以进行具体的业务处理了),注册时调用的是Selector的子类的register()方法,一个Selector可以注册多个SocketChannel
③线程通过监听 Selector 的 select() 方法(如while循环监听),该方法会返回有事件发生的通道的个数,一旦监听到有事件发生,就可以获取到发生事件的通道对应的SelectionKey的集合,进而根据事件的类型判断注册到 Selector 的 channel 的类型,进行相应的处理
示例:实现服务器端和客户端之间的非阻塞通讯
服务端:
public class NIOServer {
public static void main(String[] args) throws Exception {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
Selector selector = Selector.open();
// 监听端口
serverSocketChannel.socket().bind(new InetSocketAddress(6666));
// 设置为非阻塞
serverSocketChannel.configureBlocking(false);
// 将serverSocketChannel注册到selector,关注的事件为OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 等待客户端连接
while (true) {
if (selector.select(1000) == 0) {
System.out.println("服务端等待了1秒,无客户端连接");
continue;
}
// 获取关注事件的集合
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
// 发生新客户端连接事件
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("新客户端连接,生成socketChannel:" + socketChannel.hashCode());
// 设置为非阻塞
socketChannel.configureBlocking(false);
// 将socketChannel也注册到selector,关注OP_READ事件,并关联一个Buffer
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
// 发生读事件
if (key.isReadable()) {
// 通过key获取这个SocketChannel,注意注册的时候的类型是SocketChannel,因此获取到的也是SocketChannel类型
SocketChannel channel = (SocketChannel) key.channel();
// 获取channel关联的buffer,类型和注册时相同
ByteBuffer buffer = (ByteBuffer) key.attachment();
channel.read(buffer);
System.out.println("客户端:" + channel.hashCode() + "发送数据:" + new String(buffer.array()));
Thread.sleep(3000);
}
// 手动移除selectionKey,避免重复处理
keyIterator.remove();
}
}
}
}
注意
:在处理完通道的事件之后,会将SelectionKey从集合selectedKeys集合中移除,注意这里移除的是通过selectedKeys()方法获取到的SelectionKey——有事件发生的通道的SelectionKey,不是通过keys()获取到的,对于keys()获取到的SelectionKey不要轻易操作
客户端:
疑问
:倘若关注的事件中有一个事件处理很耗时,岂不是会导致它之后的事件处理的延迟,这时或许可以开启新线程或使用线程池来处理耗时的事件,但这不是背离了Selector的设计初衷了吗?
public class NIOClient {
public static void main(String[] args) throws Exception {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
// 服务端地址
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
if (!socketChannel.connect(inetSocketAddress)) {// 连接服务端
while (!socketChannel.finishConnect()) {
System.out.println("连接需要时间,在连接到服务端之前,客户端由于不阻塞可以做其他的事!");
}
}
String str = "Hello,world!";
ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
// 向服务端发送数据,可通过一个channel多次发送数据到服务端
socketChannel.write(buffer);
// 仅仅为了保持连接
System.in.read();
}
}
二、非阻塞网络编程用到的其他组件
1、SelectionKey
Selector 通过 SelectionKey 建立了和注册到该 Selector 上的网络通道(Channel,可能是SocketChannel,也可能是ServerSocketChannel等)的联系,根据注册时关注的事件共分四种:
①SelectionKey.OP_ACCEPT:有新的网络连接,值为 16
②SelectionKey.OP_CONNECT:代表连接已经建立,值为 8
③SelectionKey.OP_READ:代表读操作,值为 1
④SelectionKey.OP_WRITE:代表写操作,值为 4
public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;
SelectionKey 本身是一个抽象类,其常用方法如下:
public abstract class SelectionKey {
public abstract Selector selector();//得到与之关联的 Selector 对象
public abstract SelectableChannel channel();//得到与之关联的通道
public final Object attachment();//得到与之关联的共享数据
public abstract SelectionKey interestOps(int ops);//设置或改变监听事件
public final boolean isAcceptable();//是否可以 accept
public final boolean isReadable();//是否可以读
public final boolean isWritable();//是否可以写
}
2、ServerSocketChannel
ServerSocketChannel 在服务器端监听新的客户端 Socket 连接,常用方法如下:
public abstract class ServerSocketChannel extends AbstractSelectableChannel implements NetworkChannel{
public static ServerSocketChannel open(); //得到一个 ServerSocketChannel 通道
public final ServerSocketChannel bind(SocketAddress local); //设置服务器端端口号
public final SelectableChannel configureBlocking(boolean block); //设置阻塞或非阻塞模式,取值 false 表示采用非阻塞模式
public SocketChannel accept(); //接受一个连接,返回代表这个连接的通道对象
public final SelectionKey register(Selector sel, int ops); //注册到选择器并设置在该选择器上的监听事件
}
3、SocketChannel
SocketChannel,即网络 IO 通道,负责进行具体的读写等操作。NIO 把缓冲区的数据写入通道,或者把通道里的数据读到缓冲区。 SocketChannel 常用方法如下:
public abstract class SocketChannel extends AbstractSelectableChannel
implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel{
public static SocketChannel open();//得到一个 SocketChannel 通道
public final SelectableChannel configureBlocking(boolean block);//设置阻塞或非阻塞模式,取值 false 表示采用非阻塞模式
public boolean connect(SocketAddress remote);//连接服务器
public boolean finishConnect();//如果上面的方法连接失败,接下来就要通过该方法完成连接操作
public int write(ByteBuffer src);//往通道里写数据
public int read(ByteBuffer dst);//从通道里读数据
public final SelectionKey register(Selector sel, int ops, Object att);//注册到一个选择器并并设置监听事件,最后一个参数可以设置共享数据
public final void close();//关闭通道
}
当有新的客户端连接时,服务端会为新的客户端创建一个 SocketChannel,我们可以将这个 SocketChannel 注册到 Selector 中,注册的时候可以携带一些属性(register()方法的第三个参数),这个属性有时候可以给我们带来很大的帮助,比如我们可以使用这个参数进行登录认证和权限限制等,几乎所有的场景都可以通过这个参数来完成。
三、群聊系统
要求:编写一个 NIO 群聊系统,实现服务器端和客户端之间的数据非阻塞通讯; 实现多人群聊;服务器端可以监测用户上线、离线,并实现消息转发功能;客户端通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接收其它用户发送的消息(由服务器转发得到)。
服务端:
public class GroupChatServer {
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 6666;
public static void main(String[] args) {
// 创建服务端对象
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
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() {
try {
while (true) {
int count = selector.select();
if (count > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel sc = listenChannel.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
System.out.println(sc.getRemoteAddress() + " 上线 ");
}
if (key.isReadable()) {
readData(key);
}
iterator.remove();
}
} else {
System.out.println("等待...");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//
}
}
/**
* 读取客户端数据并处理
*
* @param key
*/
private void readData(SelectionKey key) {
SocketChannel channel = null;
try {
channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = channel.read(buffer);
if (count > 0) {
String msg = new String(buffer.array());
// 转发消息给其他客户端
sendMessageToOtherClients(msg, channel);
}
} catch (IOException e) {
try {
System.out.println(channel.getRemoteAddress() + " 离线了...");
key.cancel();
channel.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
/**
* 向其他客户端转发消息
*
* @param msg
* @param self
* @throws IOException
*/
private void sendMessageToOtherClients(String msg, SocketChannel self) throws IOException {
System.out.println("服务器转发消息中...");
// 遍历所有客户端
for (SelectionKey key : selector.keys()) {
SelectableChannel targetChannel = key.channel();
if (targetChannel instanceof SocketChannel && targetChannel != self) {
SocketChannel dst = (SocketChannel) targetChannel;
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
// 将消息发送给客户端
dst.write(buffer);
}
}
}
}
客户端:
public class GroupChatClient {
private static final String HOST = "127.0.0.1";
private static final int PORT = 6666;
private Selector selector;
private SocketChannel socketChannel;
private String username;
public static void main(String[] args) throws Exception {
GroupChatClient chatClient = new GroupChatClient();
// 启动一个线程每1秒读取一次服务端发送的消息
new Thread(() -> {
while (true) {
chatClient.readMessage();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
// 向服务端发送消息
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String msg = scanner.nextLine();
chatClient.sendMessage(msg);
}
}
public GroupChatClient() throws IOException {
selector = Selector.open();
socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
username = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(username + " is ok ...");
}
/**
* 发送消息
*
* @param msg
*/
public void sendMessage(String msg) {
msg = username + " 说:" + msg;
try {
socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取服务器发送的消息
*/
public void readMessage() {
try {
int readChannels = selector.select();
if (readChannels > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
sc.read(buffer);
System.out.println(new String(buffer.array()));
}
iterator.remove();
}
} else {
//
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
效果: