This commit is contained in:
Looly
2022-04-30 20:47:32 +08:00
parent dea8344d91
commit ca094ca4a8
1356 changed files with 15747 additions and 16033 deletions

View File

@@ -7,7 +7,7 @@ import java.io.Serializable;
/**
* Socket通讯配置
*
*
* @author looly
*
*/
@@ -29,10 +29,10 @@ public class SocketConfig implements Serializable{
private int readBufferSize = IoUtil.DEFAULT_BUFFER_SIZE;
/** 写出缓存大小 */
private int writeBufferSize = IoUtil.DEFAULT_BUFFER_SIZE;
/**
* 获取共享线程池大小,此线程池用于接收和处理用户连接
*
*
* @return 共享线程池大小,此线程池用于接收和处理用户连接
*/
public int getThreadPoolSize() {
@@ -41,16 +41,16 @@ public class SocketConfig implements Serializable{
/**
* 设置共享线程池大小,此线程池用于接收和处理用户连接
*
*
* @param threadPoolSize 共享线程池大小,此线程池用于接收和处理用户连接
*/
public void setThreadPoolSize(int threadPoolSize) {
public void setThreadPoolSize(final int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}
/**
* 获取读取超时时长小于等于0表示默认
*
*
* @return 读取超时时长小于等于0表示默认
*/
public long getReadTimeout() {
@@ -59,16 +59,16 @@ public class SocketConfig implements Serializable{
/**
* 设置读取超时时长小于等于0表示默认
*
*
* @param readTimeout 读取超时时长小于等于0表示默认
*/
public void setReadTimeout(long readTimeout) {
public void setReadTimeout(final long readTimeout) {
this.readTimeout = readTimeout;
}
/**
* 获取写出超时时长小于等于0表示默认
*
*
* @return 写出超时时长小于等于0表示默认
*/
public long getWriteTimeout() {
@@ -77,10 +77,10 @@ public class SocketConfig implements Serializable{
/**
* 设置写出超时时长小于等于0表示默认
*
*
* @param writeTimeout 写出超时时长小于等于0表示默认
*/
public void setWriteTimeout(long writeTimeout) {
public void setWriteTimeout(final long writeTimeout) {
this.writeTimeout = writeTimeout;
}
@@ -96,7 +96,7 @@ public class SocketConfig implements Serializable{
* 设置读取缓存大小
* @param readBufferSize 读取缓存大小
*/
public void setReadBufferSize(int readBufferSize) {
public void setReadBufferSize(final int readBufferSize) {
this.readBufferSize = readBufferSize;
}
@@ -112,7 +112,7 @@ public class SocketConfig implements Serializable{
* 设置写出缓存大小
* @param writeBufferSize 写出缓存大小
*/
public void setWriteBufferSize(int writeBufferSize) {
public void setWriteBufferSize(final int writeBufferSize) {
this.writeBufferSize = writeBufferSize;
}
}

View File

@@ -11,27 +11,27 @@ import cn.hutool.core.text.StrUtil;
public class SocketRuntimeException extends RuntimeException {
private static final long serialVersionUID = 8247610319171014183L;
public SocketRuntimeException(Throwable e) {
public SocketRuntimeException(final Throwable e) {
super(ExceptionUtil.getMessage(e), e);
}
public SocketRuntimeException(String message) {
public SocketRuntimeException(final String message) {
super(message);
}
public SocketRuntimeException(String messageTemplate, Object... params) {
public SocketRuntimeException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
}
public SocketRuntimeException(String message, Throwable throwable) {
public SocketRuntimeException(final String message, final Throwable throwable) {
super(message, throwable);
}
public SocketRuntimeException(String message, Throwable throwable, boolean enableSuppression, boolean writableStackTrace) {
public SocketRuntimeException(final String message, final Throwable throwable, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, throwable, enableSuppression, writableStackTrace);
}
public SocketRuntimeException(Throwable throwable, String messageTemplate, Object... params) {
public SocketRuntimeException(final Throwable throwable, final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params), throwable);
}
}

View File

@@ -24,13 +24,13 @@ public class SocketUtil {
* @param channel {@link AsynchronousSocketChannel}
* @return 远程端的地址信息包括host和端口null表示channel为null或者远程主机未连接
*/
public static SocketAddress getRemoteAddress(AsynchronousSocketChannel channel) {
public static SocketAddress getRemoteAddress(final AsynchronousSocketChannel channel) {
try {
return (null == channel) ? null : channel.getRemoteAddress();
} catch (ClosedChannelException e) {
} catch (final ClosedChannelException e) {
// Channel未打开或已关闭返回null表示未连接
return null;
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
}
@@ -42,7 +42,7 @@ public class SocketUtil {
* @param channel {@link AsynchronousSocketChannel}
* @return 远程主机是否处于连接状态
*/
public static boolean isConnected(AsynchronousSocketChannel channel) {
public static boolean isConnected(final AsynchronousSocketChannel channel) {
return null != getRemoteAddress(channel);
}
@@ -55,7 +55,7 @@ public class SocketUtil {
* @throws IORuntimeException IO异常
* @since 5.7.8
*/
public static Socket connect(String hostname, int port) throws IORuntimeException {
public static Socket connect(final String hostname, final int port) throws IORuntimeException {
return connect(hostname, port, -1);
}
@@ -69,7 +69,7 @@ public class SocketUtil {
* @throws IORuntimeException IO异常
* @since 5.7.8
*/
public static Socket connect(final String hostname, int port, int connectionTimeout) throws IORuntimeException {
public static Socket connect(final String hostname, final int port, final int connectionTimeout) throws IORuntimeException {
return connect(new InetSocketAddress(hostname, port), connectionTimeout);
}
@@ -82,7 +82,7 @@ public class SocketUtil {
* @throws IORuntimeException IO异常
* @since 5.7.8
*/
public static Socket connect(InetSocketAddress address, int connectionTimeout) throws IORuntimeException {
public static Socket connect(final InetSocketAddress address, final int connectionTimeout) throws IORuntimeException {
final Socket socket = new Socket();
try {
if (connectionTimeout <= 0) {
@@ -90,7 +90,7 @@ public class SocketUtil {
} else {
socket.connect(address, connectionTimeout);
}
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
return socket;

View File

@@ -8,14 +8,14 @@ import cn.hutool.log.StaticLog;
/**
* 接入完成回调,单例使用
*
*
* @author looly
*
*/
public class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AioServer> {
@Override
public void completed(AsynchronousSocketChannel socketChannel, AioServer aioServer) {
public void completed(final AsynchronousSocketChannel socketChannel, final AioServer aioServer) {
// 继续等待接入(异步)
aioServer.accept();
@@ -30,7 +30,7 @@ public class AcceptHandler implements CompletionHandler<AsynchronousSocketChanne
}
@Override
public void failed(Throwable exc, AioServer aioServer) {
public void failed(final Throwable exc, final AioServer aioServer) {
StaticLog.error(exc);
}

View File

@@ -31,7 +31,7 @@ public class AioClient implements Closeable{
* @param address 地址
* @param ioAction IO处理类
*/
public AioClient(InetSocketAddress address, IoAction<ByteBuffer> ioAction) {
public AioClient(final InetSocketAddress address, final IoAction<ByteBuffer> ioAction) {
this(address, ioAction, new SocketConfig());
}
@@ -42,7 +42,7 @@ public class AioClient implements Closeable{
* @param ioAction IO处理类
* @param config 配置项
*/
public AioClient(InetSocketAddress address, IoAction<ByteBuffer> ioAction, SocketConfig config) {
public AioClient(final InetSocketAddress address, final IoAction<ByteBuffer> ioAction, final SocketConfig config) {
this(createChannel(address, config.getThreadPoolSize()), ioAction, config);
}
@@ -53,7 +53,7 @@ public class AioClient implements Closeable{
* @param ioAction IO处理类
* @param config 配置项
*/
public AioClient(AsynchronousSocketChannel channel, IoAction<ByteBuffer> ioAction, SocketConfig config) {
public AioClient(final AsynchronousSocketChannel channel, final IoAction<ByteBuffer> ioAction, final SocketConfig config) {
this.session = new AioSession(channel, ioAction, config);
ioAction.accept(this.session);
}
@@ -68,7 +68,7 @@ public class AioClient implements Closeable{
* @return this
* @throws IOException IO异常
*/
public <T> AioClient setOption(SocketOption<T> name, T value) throws IOException {
public <T> AioClient setOption(final SocketOption<T> name, final T value) throws IOException {
this.session.getChannel().setOption(name, value);
return this;
}
@@ -98,7 +98,7 @@ public class AioClient implements Closeable{
* @param data 数据
* @return this
*/
public AioClient write(ByteBuffer data) {
public AioClient write(final ByteBuffer data) {
this.session.write(data);
return this;
}
@@ -119,22 +119,22 @@ public class AioClient implements Closeable{
* @param poolSize 线程池大小
* @return this
*/
private static AsynchronousSocketChannel createChannel(InetSocketAddress address, int poolSize) {
private static AsynchronousSocketChannel createChannel(final InetSocketAddress address, final int poolSize) {
AsynchronousSocketChannel channel;
final AsynchronousSocketChannel channel;
try {
AsynchronousChannelGroup group = AsynchronousChannelGroup.withFixedThreadPool(//
final AsynchronousChannelGroup group = AsynchronousChannelGroup.withFixedThreadPool(//
poolSize, // 默认线程池大小
ThreadFactoryBuilder.create().setNamePrefix("Huool-socket-").build()//
);
channel = AsynchronousSocketChannel.open(group);
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
try {
channel.connect(address).get();
} catch (InterruptedException | ExecutionException e) {
} catch (final InterruptedException | ExecutionException e) {
IoUtil.close(channel);
throw new SocketRuntimeException(e);
}

View File

@@ -36,7 +36,7 @@ public class AioServer implements Closeable {
*
* @param port 端口
*/
public AioServer(int port) {
public AioServer(final int port) {
this(new InetSocketAddress(port), new SocketConfig());
}
@@ -46,7 +46,7 @@ public class AioServer implements Closeable {
* @param address 地址
* @param config {@link SocketConfig} 配置项
*/
public AioServer(InetSocketAddress address, SocketConfig config) {
public AioServer(final InetSocketAddress address, final SocketConfig config) {
this.config = config;
init(address);
}
@@ -57,14 +57,14 @@ public class AioServer implements Closeable {
* @param address 地址和端口
* @return this
*/
public AioServer init(InetSocketAddress address) {
public AioServer init(final InetSocketAddress address) {
try {
this.group = AsynchronousChannelGroup.withFixedThreadPool(//
config.getThreadPoolSize(), // 默认线程池大小
ThreadFactoryBuilder.create().setNamePrefix("Hutool-socket-").build()//
);
this.channel = AsynchronousServerSocketChannel.open(group).bind(address);
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
return this;
@@ -75,7 +75,7 @@ public class AioServer implements Closeable {
*
* @param sync 是否阻塞
*/
public void start(boolean sync) {
public void start(final boolean sync) {
doStart(sync);
}
@@ -89,7 +89,7 @@ public class AioServer implements Closeable {
* @return this
* @throws IOException IO异常
*/
public <T> AioServer setOption(SocketOption<T> name, T value) throws IOException {
public <T> AioServer setOption(final SocketOption<T> name, final T value) throws IOException {
this.channel.setOption(name, value);
return this;
}
@@ -109,7 +109,7 @@ public class AioServer implements Closeable {
* @param ioAction {@link IoAction}
* @return this;
*/
public AioServer setIoAction(IoAction<ByteBuffer> ioAction) {
public AioServer setIoAction(final IoAction<ByteBuffer> ioAction) {
this.ioAction = ioAction;
return this;
}
@@ -152,7 +152,7 @@ public class AioServer implements Closeable {
if (null != this.group && false == this.group.isShutdown()) {
try {
this.group.shutdownNow();
} catch (IOException e) {
} catch (final IOException e) {
// ignore
}
}
@@ -170,7 +170,7 @@ public class AioServer implements Closeable {
*
* @param sync 是否阻塞
*/
private void doStart(boolean sync) {
private void doStart(final boolean sync) {
log.debug("Aio Server started, waiting for accept.");
// 接收客户端连接

View File

@@ -17,7 +17,7 @@ import java.util.concurrent.TimeUnit;
/**
* AIO会话<br>
* 每个客户端对应一个会话对象
*
*
* @author looly
*
*/
@@ -36,12 +36,12 @@ public class AioSession implements Closeable{
/**
* 构造
*
*
* @param channel {@link AsynchronousSocketChannel}
* @param ioAction IO消息处理类
* @param config 配置项
*/
public AioSession(AsynchronousSocketChannel channel, IoAction<ByteBuffer> ioAction, SocketConfig config) {
public AioSession(final AsynchronousSocketChannel channel, final IoAction<ByteBuffer> ioAction, final SocketConfig config) {
this.channel = channel;
this.ioAction = ioAction;
@@ -53,7 +53,7 @@ public class AioSession implements Closeable{
/**
* 获取{@link AsynchronousSocketChannel}
*
*
* @return {@link AsynchronousSocketChannel}
*/
public AsynchronousSocketChannel getChannel() {
@@ -62,7 +62,7 @@ public class AioSession implements Closeable{
/**
* 获取读取Buffer
*
*
* @return 读取Buffer
*/
public ByteBuffer getReadBuffer() {
@@ -71,7 +71,7 @@ public class AioSession implements Closeable{
/**
* 获取写Buffer
*
*
* @return 写Buffer
*/
public ByteBuffer getWriteBuffer() {
@@ -80,7 +80,7 @@ public class AioSession implements Closeable{
/**
* 获取消息处理器
*
*
* @return {@link IoAction}
*/
public IoAction<ByteBuffer> getIoAction() {
@@ -89,7 +89,7 @@ public class AioSession implements Closeable{
/**
* 获取远程主机(客户端)地址和端口
*
*
* @return 远程主机(客户端)地址和端口
*/
public SocketAddress getRemoteAddress() {
@@ -98,7 +98,7 @@ public class AioSession implements Closeable{
/**
* 读取数据到Buffer
*
*
* @return this
*/
public AioSession read() {
@@ -107,11 +107,11 @@ public class AioSession implements Closeable{
/**
* 读取数据到Buffer
*
*
* @param handler {@link CompletionHandler}
* @return this
*/
public AioSession read(CompletionHandler<Integer, AioSession> handler) {
public AioSession read(final CompletionHandler<Integer, AioSession> handler) {
if (isOpen()) {
this.readBuffer.clear();
this.channel.read(this.readBuffer, Math.max(this.readTimeout, 0L), TimeUnit.MILLISECONDS, this, handler);
@@ -125,7 +125,7 @@ public class AioSession implements Closeable{
* @param data 数据
* @return this
*/
public AioSession writeAndClose(ByteBuffer data) {
public AioSession writeAndClose(final ByteBuffer data) {
write(data);
return closeOut();
}
@@ -136,7 +136,7 @@ public class AioSession implements Closeable{
* @param data 数据
* @return {@link Future}
*/
public Future<Integer> write(ByteBuffer data) {
public Future<Integer> write(final ByteBuffer data) {
return this.channel.write(data);
}
@@ -147,7 +147,7 @@ public class AioSession implements Closeable{
* @param handler {@link CompletionHandler}
* @return this
*/
public AioSession write(ByteBuffer data, CompletionHandler<Integer, AioSession> handler) {
public AioSession write(final ByteBuffer data, final CompletionHandler<Integer, AioSession> handler) {
this.channel.write(data, Math.max(this.writeTimeout, 0L), TimeUnit.MILLISECONDS, this, handler);
return this;
}
@@ -155,7 +155,7 @@ public class AioSession implements Closeable{
/**
* 会话是否打开状态<br>
* 当Socket保持连接时会话始终打开
*
*
* @return 会话是否打开状态
*/
public boolean isOpen() {
@@ -164,14 +164,14 @@ public class AioSession implements Closeable{
/**
* 关闭输出
*
*
* @return this
*/
public AioSession closeIn() {
if (null != this.channel) {
try {
this.channel.shutdownInput();
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
}
@@ -180,14 +180,14 @@ public class AioSession implements Closeable{
/**
* 关闭输出
*
*
* @return this
*/
public AioSession closeOut() {
if (null != this.channel) {
try {
this.channel.shutdownOutput();
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
}

View File

@@ -6,19 +6,19 @@ import cn.hutool.socket.SocketRuntimeException;
/**
* 数据读取完成回调调用Session中相应方法处理消息单例使用
*
*
* @author looly
*
*/
public class ReadHandler implements CompletionHandler<Integer, AioSession> {
@Override
public void completed(Integer result, AioSession session) {
public void completed(final Integer result, final AioSession session) {
session.callbackRead();
}
@Override
public void failed(Throwable exc, AioSession session) {
public void failed(final Throwable exc, final AioSession session) {
throw new SocketRuntimeException(exc);
}

View File

@@ -7,18 +7,18 @@ import cn.hutool.log.StaticLog;
/**
* 简易IO信息处理类<br>
* 简单实现了accept和failed事件
*
*
* @author looly
*
*/
public abstract class SimpleIoAction implements IoAction<ByteBuffer> {
@Override
public void accept(AioSession session) {
public void accept(final AioSession session) {
}
@Override
public void failed(Throwable exc, AioSession session) {
public void failed(final Throwable exc, final AioSession session) {
StaticLog.error(exc);
}
}

View File

@@ -10,19 +10,19 @@ import java.nio.channels.SocketChannel;
/**
* 接入完成回调,单例使用
*
*
* @author looly
*/
public class AcceptHandler implements CompletionHandler<ServerSocketChannel, NioServer> {
@Override
public void completed(ServerSocketChannel serverSocketChannel, NioServer nioServer) {
SocketChannel socketChannel;
public void completed(final ServerSocketChannel serverSocketChannel, final NioServer nioServer) {
final SocketChannel socketChannel;
try {
// 获取连接到此服务器的客户端通道
socketChannel = serverSocketChannel.accept();
StaticLog.debug("Client [{}] accepted.", socketChannel.getRemoteAddress());
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
@@ -31,7 +31,7 @@ public class AcceptHandler implements CompletionHandler<ServerSocketChannel, Nio
}
@Override
public void failed(Throwable exc, NioServer nioServer) {
public void failed(final Throwable exc, final NioServer nioServer) {
StaticLog.error(exc);
}

View File

@@ -32,7 +32,7 @@ public class NioClient implements Closeable {
* @param host 服务器地址
* @param port 端口
*/
public NioClient(String host, int port) {
public NioClient(final String host, final int port) {
init(new InetSocketAddress(host, port));
}
@@ -41,7 +41,7 @@ public class NioClient implements Closeable {
*
* @param address 服务器地址
*/
public NioClient(InetSocketAddress address) {
public NioClient(final InetSocketAddress address) {
init(address);
}
@@ -51,7 +51,7 @@ public class NioClient implements Closeable {
* @param address 地址和端口
* @return this
*/
public NioClient init(InetSocketAddress address) {
public NioClient init(final InetSocketAddress address) {
try {
//创建一个SocketChannel对象配置成非阻塞模式
this.channel = SocketChannel.open();
@@ -65,7 +65,7 @@ public class NioClient implements Closeable {
// 等待建立连接
//noinspection StatementWithEmptyBody
while (false == channel.finishConnect()){}
} catch (IOException e) {
} catch (final IOException e) {
close();
throw new IORuntimeException(e);
}
@@ -78,7 +78,7 @@ public class NioClient implements Closeable {
* @param handler {@link ChannelHandler}
* @return this
*/
public NioClient setChannelHandler(ChannelHandler handler){
public NioClient setChannelHandler(final ChannelHandler handler){
this.handler = handler;
return this;
}
@@ -90,7 +90,7 @@ public class NioClient implements Closeable {
ThreadUtil.execute(() -> {
try {
doListen();
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
}
});
@@ -117,13 +117,13 @@ public class NioClient implements Closeable {
*
* @param key SelectionKey
*/
private void handle(SelectionKey key) {
private void handle(final SelectionKey key) {
// 读事件就绪
if (key.isReadable()) {
final SocketChannel socketChannel = (SocketChannel) key.channel();
try{
handler.handle(socketChannel);
} catch (Exception e){
} catch (final Exception e){
throw new SocketRuntimeException(e);
}
}
@@ -136,10 +136,10 @@ public class NioClient implements Closeable {
* @param datas 发送的数据
* @return this
*/
public NioClient write(ByteBuffer... datas) {
public NioClient write(final ByteBuffer... datas) {
try {
this.channel.write(datas);
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
return this;

View File

@@ -16,7 +16,7 @@ import java.util.Iterator;
/**
* 基于NIO的Socket服务端实现
*
*
* @author looly
*
*/
@@ -31,20 +31,20 @@ public class NioServer implements Closeable {
/**
* 构造
*
*
* @param port 端口
*/
public NioServer(int port) {
public NioServer(final int port) {
init(new InetSocketAddress(port));
}
/**
* 初始化
*
*
* @param address 地址和端口
* @return this
*/
public NioServer init(InetSocketAddress address) {
public NioServer init(final InetSocketAddress address) {
try {
// 打开服务器套接字通道
this.serverSocketChannel = ServerSocketChannel.open();
@@ -57,7 +57,7 @@ public class NioServer implements Closeable {
this.selector = Selector.open();
// 服务器套接字注册到Selector中 并指定Selector监控连接事件
this.serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
@@ -72,7 +72,7 @@ public class NioServer implements Closeable {
* @param handler {@link ChannelHandler}
* @return this
*/
public NioServer setChannelHandler(ChannelHandler handler){
public NioServer setChannelHandler(final ChannelHandler handler){
this.handler = handler;
return this;
}
@@ -101,14 +101,14 @@ public class NioServer implements Closeable {
public void listen() {
try {
doListen();
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
}
/**
* 开始监听
*
*
* @throws IOException IO异常
*/
private void doListen() throws IOException {
@@ -124,10 +124,10 @@ public class NioServer implements Closeable {
/**
* 处理SelectionKey
*
*
* @param key SelectionKey
*/
private void handle(SelectionKey key) {
private void handle(final SelectionKey key) {
// 有客户端接入此服务端
if (key.isAcceptable()) {
ACCEPT_HANDLER.completed((ServerSocketChannel) key.channel(), this);
@@ -138,7 +138,7 @@ public class NioServer implements Closeable {
final SocketChannel socketChannel = (SocketChannel) key.channel();
try{
handler.handle(socketChannel);
} catch (Exception e){
} catch (final Exception e){
IoUtil.close(socketChannel);
StaticLog.error(e);
}

View File

@@ -20,7 +20,7 @@ public class NioUtil {
* @param channel 通道
* @param ops 注册的通道监听(操作)类型
*/
public static void registerChannel(Selector selector, SelectableChannel channel, Operation ops) {
public static void registerChannel(final Selector selector, final SelectableChannel channel, final Operation ops) {
if (channel == null) {
return;
}
@@ -30,7 +30,7 @@ public class NioUtil {
// 注册通道
//noinspection MagicConstant
channel.register(selector, ops.getValue());
} catch (IOException e) {
} catch (final IOException e) {
throw new IORuntimeException(e);
}
}

View File

@@ -4,7 +4,7 @@ import java.nio.channels.SelectionKey;
/**
* SelectionKey Operation的枚举封装
*
*
* @author looly
*/
public enum Operation {
@@ -22,20 +22,20 @@ public enum Operation {
/**
* 构造
*
*
* @param value 值
* @see SelectionKey#OP_READ
* @see SelectionKey#OP_WRITE
* @see SelectionKey#OP_CONNECT
* @see SelectionKey#OP_ACCEPT
*/
Operation(int value) {
Operation(final int value) {
this.value = value;
}
/**
* 获取值
*
*
* @return 值
* @see SelectionKey#OP_READ
* @see SelectionKey#OP_WRITE

View File

@@ -7,11 +7,11 @@ import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
public class AioClientTest {
public static void main(String[] args) {
AioClient client = new AioClient(new InetSocketAddress("localhost", 8899), new SimpleIoAction() {
public static void main(final String[] args) {
final AioClient client = new AioClient(new InetSocketAddress("localhost", 8899), new SimpleIoAction() {
@Override
public void doAction(AioSession session, ByteBuffer data) {
public void doAction(final AioSession session, final ByteBuffer data) {
if(data.hasRemaining()) {
Console.log(StrUtil.utf8Str(data));
session.read();

View File

@@ -10,24 +10,23 @@ import java.nio.ByteBuffer;
public class AioServerTest {
public static void main(String[] args) {
public static void main(final String[] args) {
@SuppressWarnings("resource")
AioServer aioServer = new AioServer(8899);
@SuppressWarnings("resource") final AioServer aioServer = new AioServer(8899);
aioServer.setIoAction(new SimpleIoAction() {
@Override
public void accept(AioSession session) {
public void accept(final AioSession session) {
StaticLog.debug("【客户端】:{} 连接。", session.getRemoteAddress());
session.write(BufferUtil.createUtf8("=== Welcome to Hutool socket server. ==="));
}
@Override
public void doAction(AioSession session, ByteBuffer data) {
public void doAction(final AioSession session, final ByteBuffer data) {
Console.log(data);
if(false == data.hasRemaining()) {
StringBuilder response = StrUtil.builder()//
final StringBuilder response = StrUtil.builder()//
.append("HTTP/1.1 200 OK\r\n")//
.append("Date: ").append(DateUtil.formatHttpDate(DateUtil.date())).append("\r\n")//
.append("Content-Type: text/html; charset=UTF-8\r\n")//

View File

@@ -11,22 +11,22 @@ import java.util.Scanner;
public class NioClientTest {
@SneakyThrows
public static void main(String[] args) {
NioClient client = new NioClient("127.0.0.1", 8080);
public static void main(final String[] args) {
final NioClient client = new NioClient("127.0.0.1", 8080);
client.setChannelHandler((sc)->{
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
final ByteBuffer readBuffer = ByteBuffer.allocate(1024);
//从channel读数据到缓冲区
int readBytes = sc.read(readBuffer);
final int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
//Flips this buffer. The limit is set to the current position and then
// the position is set to zero就是表示要从起始位置开始读取数据
readBuffer.flip();
//returns the number of elements between the current position and the limit.
// 要读取的字节长度
byte[] bytes = new byte[readBuffer.remaining()];
final byte[] bytes = new byte[readBuffer.remaining()];
//将缓冲区的数据读到bytes数组
readBuffer.get(bytes);
String body = StrUtil.utf8Str(bytes);
final String body = StrUtil.utf8Str(bytes);
Console.log("[{}]: {}", sc.getRemoteAddress(), body);
} else if (readBytes < 0) {
sc.close();
@@ -39,9 +39,9 @@ public class NioClientTest {
// 在控制台向服务器端发送数据
Console.log("请输入发送的消息:");
Scanner scanner = new Scanner(System.in);
final Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String request = scanner.nextLine();
final String request = scanner.nextLine();
if (request != null && request.trim().length() > 0) {
client.write(BufferUtil.createUtf8(request));
}

View File

@@ -12,37 +12,37 @@ import java.nio.channels.SocketChannel;
public class NioServerTest {
public static void main(String[] args) {
NioServer server = new NioServer(8080);
public static void main(final String[] args) {
final NioServer server = new NioServer(8080);
server.setChannelHandler((sc)->{
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
final ByteBuffer readBuffer = ByteBuffer.allocate(1024);
try{
//从channel读数据到缓冲区
int readBytes = sc.read(readBuffer);
final int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
//Flips this buffer. The limit is set to the current position and then
// the position is set to zero就是表示要从起始位置开始读取数据
readBuffer.flip();
//eturns the number of elements between the current position and the limit.
// 要读取的字节长度
byte[] bytes = new byte[readBuffer.remaining()];
final byte[] bytes = new byte[readBuffer.remaining()];
//将缓冲区的数据读到bytes数组
readBuffer.get(bytes);
String body = StrUtil.utf8Str(bytes);
final String body = StrUtil.utf8Str(bytes);
Console.log("[{}]: {}", sc.getRemoteAddress(), body);
doWrite(sc, body);
} else if (readBytes < 0) {
IoUtil.close(sc);
}
} catch (IOException e){
} catch (final IOException e){
throw new IORuntimeException(e);
}
});
server.listen();
}
public static void doWrite(SocketChannel channel, String response) throws IOException {
public static void doWrite(final SocketChannel channel, String response) throws IOException {
response = "收到消息:" + response;
//将缓冲数据写入渠道,返回给客户端
channel.write(BufferUtil.createUtf8(response));