多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
~~~ public class EchoServer { private final int port; public EchoServer(int port) { this.port = port; } /** * 1. 创建ServerBootstrap实例,并制定NioEventLoopGroup来接收和处理新的连接 * 2. 设置channel的类型为NioServerSocketChannel * 3. 设置地址端口,服务器将绑定这个地址以监听新的请求连接 * 4. ChannelInitializer, 新的连接被接受时,一个新的子Channel被创建,ChannelInitializer会把你的 * EchoServerHandler添加到该Channel的ChannelPipeline中 * 5. EchoServerHandler将会接收到信息 * 6. 等待绑定完成,sync方法将当前Thread阻塞,一致到绑定操作完成为止 * 7. 应用程序将会阻塞等待知道服务器的Channel关闭,因为你再Channel.CloseFuture调用了sync方法 * 8. 关闭EventLoopGroup,释放所有资源,包括被创建的线程 */ public void start() throws Exception{ EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) // 指定使用的Nio传输Channel .localAddress(new InetSocketAddress(port))//指定端口设置套接字地址 .childHandler(new ChannelInitializer<SocketChannel>() {// 添加EchoServerHandler到子Channel的ChannelPipline protected void initChannel(SocketChannel socketChannel) throws Exception { // EchoServerHandler被标记为@Shareable,所以我们可以总是使用这样的实例 socketChannel.pipeline().addLast(new EchoServerHandler()); } }); // 6. 异步绑定服务器,调用sync方法阻塞等待知道绑定完成 ChannelFuture f = b.bind().sync(); // 7. 获取Channel的CloseFuture,并且阻塞当前线程直到它完成 f.channel().closeFuture().sync(); } finally { // 关闭EventLoopGroup释放所有资源 group.shutdownGracefully().sync(); } } public static void main(String[] args) { try { new EchoServer(10001).start(); }catch (Exception e){ System.out.println("服务端启动异常"); e.printStackTrace(); } } } ~~~