This commit is contained in:
Looly
2020-08-01 19:23:55 +08:00
parent 04917da6e2
commit 02b0f6194f
5 changed files with 60 additions and 57 deletions

View File

@@ -6,12 +6,14 @@ import java.nio.channels.SocketChannel;
* NIO数据处理接口通过实现此接口可以从{@link SocketChannel}中读写数据
*
*/
@FunctionalInterface
public interface ChannelHandler {
/**
* 处理NIO数据
*
* @param socketChannel {@link SocketChannel}
* @throws Exception 可能的处理异常
*/
void handle(SocketChannel socketChannel);
void handle(SocketChannel socketChannel) throws Exception;
}

View File

@@ -3,6 +3,7 @@ package cn.hutool.socket.nio;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.socket.SocketRuntimeException;
import java.io.Closeable;
import java.io.IOException;
@@ -19,9 +20,11 @@ import java.util.Iterator;
* @author looly
* @since 4.4.5
*/
public abstract class NioClient implements Closeable {
public class NioClient implements Closeable {
private Selector selector;
private SocketChannel channel;
private ChannelHandler handler;
/**
* 构造
@@ -68,6 +71,17 @@ public abstract class NioClient implements Closeable {
return this;
}
/**
* 设置NIO数据处理器
*
* @param handler {@link ChannelHandler}
* @return this
*/
public NioClient setChannelHandler(ChannelHandler handler){
this.handler = handler;
return this;
}
/**
* 开始监听
*/
@@ -106,18 +120,14 @@ public abstract class NioClient implements Closeable {
// 读事件就绪
if (key.isReadable()) {
final SocketChannel socketChannel = (SocketChannel) key.channel();
read(socketChannel);
try{
handler.handle(socketChannel);
} catch (Exception e){
throw new SocketRuntimeException(e);
}
}
}
/**
* 处理读事件<br>
* 当收到读取准备就绪的信号后,回调此方法,用户可读取从客户端传出来的消息
*
* @param socketChannel SocketChannel
*/
protected abstract void read(SocketChannel socketChannel);
/**
* 实现写逻辑<br>
* 当收到写出准备就绪的信号后,回调此方法,用户可向客户端发送消息

View File

@@ -3,6 +3,7 @@ package cn.hutool.socket.nio;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import java.io.Closeable;
import java.io.IOException;
@@ -135,7 +136,12 @@ public class NioServer implements Closeable {
// 读事件就绪
if (key.isReadable()) {
final SocketChannel socketChannel = (SocketChannel) key.channel();
handler.handle(socketChannel);
try{
handler.handle(socketChannel);
} catch (Exception e){
IoUtil.close(socketChannel);
StaticLog.error(e);
}
}
}