1.创建maven项目并引入依赖

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-all</artifactId>
  4. <version>5.0.0.Alpha2</version>
  5. </dependency>

2.编写服务端代码

  1. import io.netty.bootstrap.ServerBootstrap;
  2. import io.netty.channel.ChannelFuture;
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.ChannelOption;
  5. import io.netty.channel.nio.NioEventLoopGroup;
  6. import io.netty.channel.socket.SocketChannel;
  7. import io.netty.channel.socket.nio.NioServerSocketChannel;
  8. /**
  9. * @author 冯铁城 [17615007230@163.com]
  10. * @date 2022-05-09 19:11:57
  11. * @describe: 时间服务器服务端
  12. */
  13. public class TimeServer {
  14. public static void main(String[] args) {
  15. int port = 8080;
  16. if(null != args && 0 < args.length){
  17. port = Integer.parseInt(args[0]);
  18. }
  19. new TimeServer().bind(port);
  20. }
  21. public void bind(int port) {
  22. //1.创建线程组用于接受服务端链接
  23. NioEventLoopGroup bossGroup = new NioEventLoopGroup();
  24. //2.创建线程组用户socketChannel读写
  25. NioEventLoopGroup workGroup = new NioEventLoopGroup();
  26. try {
  27. //3.创建服务端
  28. ServerBootstrap server = new ServerBootstrap();
  29. server.group(bossGroup, workGroup)
  30. .channel(NioServerSocketChannel.class)
  31. .option(ChannelOption.SO_BACKLOG, 1024)
  32. .childHandler(new ChildChannelHandler());
  33. //3.绑定端口,开启同步等
  34. ChannelFuture sync = server.bind(port).sync();
  35. System.out.println("服务端已启动!");
  36. //4.等待服务端监听端口关闭
  37. sync.channel().closeFuture().sync();
  38. } catch (InterruptedException e) {
  39. e.printStackTrace();
  40. }finally {
  41. bossGroup.shutdownGracefully();
  42. workGroup.shutdownGracefully();
  43. }
  44. }
  45. private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
  46. @Override
  47. protected void initChannel(SocketChannel socketChannel) throws Exception {
  48. socketChannel.pipeline().addLast(new TimeServerHandler());
  49. }
  50. }
  51. }
  1. 创建用于接收客户端链接线程组、负责socketIO的线程组
  2. 开启Netty服务端
  3. 服务端配置线程组、渠道、配置TCP参数、定义IO事件处理类
  4. 同步绑定端口开启
  5. 最终优雅退出线程
  6. IO时间处理类添加具体IO处理类

    3.编写具体IO处理类

    ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext;

import java.util.Scanner;

/**

  • @author 冯铁城 [17615007230@163.com]
  • @date 2022-05-09 20:41:33
  • @describe: 时间服务器服务端 */ public class TimeServerHandler extends ChannelHandlerAdapter {

    private static final Scanner SCANNER = new Scanner(System.in);

    @Override public void channelActive(ChannelHandlerContext ctx) throws Exception {

    1. System.out.println("服务端已与" + ctx.channel().id() + "建立链接");

    }

    @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    1. //1.读取消息为字节数组
    2. ByteBuf buf = (ByteBuf) msg;
    3. byte[] bytes = new byte[buf.readableBytes()];
    4. buf.readBytes(bytes);
    5. //2.字符串判定
    6. String body = new String(bytes, "UTF-8");
    7. System.out.println("收到" + ctx.channel().id() + "渠道的请求:" + body);
    8. //3.定义返回结果
    9. System.out.println("请输入响应信息");
    10. String responseMessage = SCANNER.nextLine();
    11. //4.相应数据
    12. ByteBuf response = Unpooled.copiedBuffer(responseMessage.getBytes());
    13. ctx.write(response);

    }

    @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    1. ctx.flush();

    }

    @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    1. ctx.close();

    } } ```

  1. 继承ChannelHandlerAdapter类
  2. 重写channelActive方法,当客户端或服务端建立链接时,触发此方法
  3. 重写channelRead方法,当客户端