1. @Slf4j
    2. public class EchoServer {
    3. public static void main(String[] args) {
    4. new ServerBootstrap()
    5. .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
    6. .channel(NioServerSocketChannel.class)
    7. .childHandler(new ChannelInitializer<NioSocketChannel>() {
    8. @Override
    9. protected void initChannel(NioSocketChannel ch) throws Exception {
    10. ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
    11. @Override
    12. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    13. ByteBuf byteBuf = (ByteBuf) msg;
    14. log.info(ch.remoteAddress() + "消息:" + byteBuf.toString(Charset.defaultCharset()));
    15. String serverMsg = "服务端已接收到" + ch.remoteAddress() + "消息:" + byteBuf.toString(Charset.defaultCharset());
    16. ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(serverMsg.getBytes(StandardCharsets.UTF_8)))
    17. .addListener(new ChannelFutureListener() {
    18. @Override
    19. public void operationComplete(ChannelFuture channelFuture) throws Exception {
    20. if(!channelFuture.isSuccess()){
    21. log.info("服务端消息发送失败: 客户端信息--- {} ,消息内容--- {}",ch.remoteAddress() ,serverMsg);
    22. }
    23. }
    24. });
    25. }
    26. @Override
    27. public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    28. log.info(ctx.channel().remoteAddress() + "客户端连接成功");
    29. super.channelRegistered(ctx);
    30. }
    31. @Override
    32. public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    33. log.info(ctx.channel().remoteAddress() + "客户端断开连接");
    34. super.channelUnregistered(ctx);
    35. }
    36. });
    37. }
    38. }).bind(8989);
    39. }
    40. }
    1. @Slf4j
    2. public class EchoClient {
    3. public static void main(String[] args) throws InterruptedException {
    4. final Channel channel = new Bootstrap()
    5. .group(new NioEventLoopGroup())
    6. .channel(NioSocketChannel.class)
    7. .handler(new ChannelInitializer<NioSocketChannel>() {
    8. @Override
    9. protected void initChannel(NioSocketChannel ch) throws Exception {
    10. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
    11. @Override
    12. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    13. ByteBuf byteBuf = (ByteBuf) msg;
    14. System.out.println("客户端接收消息:" + ch.remoteAddress() + "消息:" + byteBuf.toString(Charset.defaultCharset()));
    15. byteBuf.release();
    16. }
    17. }).addLast(new StringEncoder());
    18. }
    19. }).connect(new InetSocketAddress("127.0.0.1", 8989)).sync().channel();
    20. Scanner scanner = new Scanner(System.in);
    21. while (scanner.hasNext()) {
    22. String str = scanner.next();
    23. if(!"quit".equals(str)){
    24. channel.writeAndFlush(str);
    25. }else {
    26. channel.close().sync();
    27. log.info("客户端断开");
    28. }
    29. }
    30. }
    31. }