50,526
社区成员
发帖
与我相关
我的任务
分享
public void bind() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder(Charset.forName("utf-8")));
pipeline.addLast(new StringEncoder(Charset.forName("utf-8")));
pipeline.addLast(new NettyServerHandler());
}
});
bootstrap.bind("127.0.0.1", 5000).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.write("Welcome to" + InetAddress.getLocalHost().getHostName() + "!\r\n");
ctx.flush();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
LogUtil.log("server channelRead0 : " + request);
String response = "server receive : " + request;
boolean close = false;
if (request.indexOf("bye") == 0) {
close = true;
response = "系统退出" + "\r\n";
}
ChannelFuture future = ctx.writeAndFlush(response);
if (close) {
// future.addListener(ChannelFutureListener.CLOSE).sync().channel().closeFuture().sync();
future.addListener(ChannelFutureListener.CLOSE);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
public void connect() throws InterruptedException {
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder(Charset.forName("utf-8")));
pipeline.addLast(new StringEncoder(Charset.forName("utf-8")));
pipeline.addLast(new NettyClientHandler());
}
});
bootstrap.connect("127.0.0.1", 5000).sync().channel().closeFuture().sync();
} finally {
}
}
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg)
throws Exception {
LogUtil.log("client channelRead0 : " + msg);
if (msg.contains("系统退出")) {
LogUtil.log("client ctx.close()");
ctx.close();
} else {
ctx.writeAndFlush("aaa");
ctx.writeAndFlush("bye");
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}