|
| 1 | +package com.cpucode.netty.customize.protocol.server; |
| 2 | + |
| 3 | +import com.cpucode.netty.customize.protocol.SmartCarDecoder; |
| 4 | +import com.cpucode.netty.customize.protocol.SmartCarEncoder; |
| 5 | +import io.netty.bootstrap.ServerBootstrap; |
| 6 | +import io.netty.channel.ChannelFuture; |
| 7 | +import io.netty.channel.ChannelInitializer; |
| 8 | +import io.netty.channel.ChannelOption; |
| 9 | +import io.netty.channel.EventLoopGroup; |
| 10 | +import io.netty.channel.nio.NioEventLoopGroup; |
| 11 | +import io.netty.channel.socket.SocketChannel; |
| 12 | +import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 13 | +import io.netty.handler.logging.LogLevel; |
| 14 | +import io.netty.handler.logging.LoggingHandler; |
| 15 | + |
| 16 | +/** |
| 17 | + * @author : cpucode |
| 18 | + * @date : 2021/8/19 13:10 |
| 19 | + * @github : https://github.com/CPU-Code |
| 20 | + * @csdn : https://blog.csdn.net/qq_44226094 |
| 21 | + */ |
| 22 | +public class Server { |
| 23 | + public Server() { |
| 24 | + } |
| 25 | + |
| 26 | + public void bind(int port) throws Exception { |
| 27 | + // 配置NIO线程组 |
| 28 | + EventLoopGroup bossGroup = new NioEventLoopGroup(); |
| 29 | + EventLoopGroup workerGroup = new NioEventLoopGroup(); |
| 30 | + try { |
| 31 | + // 服务器辅助启动类配置 |
| 32 | + ServerBootstrap b = new ServerBootstrap(); |
| 33 | + b.group(bossGroup, workerGroup) |
| 34 | + .channel(NioServerSocketChannel.class) |
| 35 | + .handler(new LoggingHandler(LogLevel.INFO)) |
| 36 | + .childHandler(new ChildChannelHandler())// |
| 37 | + .option(ChannelOption.SO_BACKLOG, 1024) // 设置tcp缓冲区 // (5) |
| 38 | + .childOption(ChannelOption.SO_KEEPALIVE, true); // (6) |
| 39 | + // 绑定端口 同步等待绑定成功 |
| 40 | + ChannelFuture f = b.bind(port).sync(); // (7) |
| 41 | + // 等到服务端监听端口关闭 |
| 42 | + f.channel().closeFuture().sync(); |
| 43 | + } finally { |
| 44 | + // 优雅释放线程资源 |
| 45 | + workerGroup.shutdownGracefully(); |
| 46 | + bossGroup.shutdownGracefully(); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * 网络事件处理器 |
| 52 | + */ |
| 53 | + private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { |
| 54 | + @Override |
| 55 | + protected void initChannel(SocketChannel ch) throws Exception { |
| 56 | + // 添加自定义协议的编解码工具 |
| 57 | + ch.pipeline().addLast(new SmartCarEncoder()); |
| 58 | + ch.pipeline().addLast(new SmartCarDecoder()); |
| 59 | + // 处理网络IO |
| 60 | + ch.pipeline().addLast(new ServerHandler()); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + public static void main(String[] args) throws Exception { |
| 65 | + new Server().bind(9999); |
| 66 | + } |
| 67 | +} |
0 commit comments