归档
JDK-示例
- ref: https://github.com/zengxf/small-frame-demo/tree/master/jdk-demo/simple-demo/src/main/java/test/socket/nio
Netty-示例
服务端
package io.netty.handler.codec.mytest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import java.net.InetSocketAddress;
public class MyServerTest {
static int PORT = 8899;
public static void main(String[] args) throws InterruptedException {
EventLoopGroup elg = new NioEventLoopGroup(2);
ServerBootstrap sb = new ServerBootstrap();
sb.group(elg);
sb.channel(NioServerSocketChannel.class);
sb.localAddress(new InetSocketAddress(PORT));
sb.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel sc) {
sc.pipeline().addLast("toStr", new StringDecoder());
sc.pipeline().addLast("test", new TestHandler());
}
});
ChannelFuture cf = sb.bind().sync();
System.out.println("启动完成 -------------");
cf.channel().closeFuture().sync();
System.out.println("关闭完成 -------------");
elg.shutdownGracefully();
}
static class TestHandler extends ChannelInboundHandlerAdapter {
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
new RuntimeException("栈跟踪-处理器被添加").printStackTrace();
super.handlerAdded(ctx);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
new RuntimeException("栈跟踪-处理器被注册").printStackTrace();
super.channelRegistered(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("读取消息:" + msg);
super.channelRead(ctx, msg);
}
}
}
客户端
package io.netty.handler.codec.mytest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.time.LocalTime;
public class MyClientTest {
public static void main(String[] args) {
EventLoopGroup elg = new NioEventLoopGroup(1);
Bootstrap cb = new Bootstrap();
cb.group(elg);
cb.channel(NioSocketChannel.class);
cb.remoteAddress("localhost", MyServerTest.PORT);
cb.handler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast("toByte", new StringEncoder());
}
});
System.out.println("客户端开始连接...");
ChannelFuture cf = cb.connect();
cf.addListener((ChannelFuture f) -> {
if (f.isSuccess()) {
System.out.println("连接成功!");
String msg = "中-Test 123..." + LocalTime.now();
Channel channel = f.channel();
channel.write(msg);
System.out.println("发送消息:" + msg);
channel.flush();
channel.close().sync();
elg.shutdownGracefully();
} else {
System.out.println("连接还未成功!");
}
});
}
}