|
| 1 | +package com.ipman.netty.springboot.sample.echo; |
| 2 | + |
| 3 | +import io.netty.bootstrap.ServerBootstrap; |
| 4 | +import io.netty.channel.ChannelFuture; |
| 5 | +import io.netty.channel.ChannelInitializer; |
| 6 | +import io.netty.channel.ChannelPipeline; |
| 7 | +import io.netty.channel.EventLoopGroup; |
| 8 | +import io.netty.channel.nio.NioEventLoopGroup; |
| 9 | +import io.netty.channel.socket.SocketChannel; |
| 10 | +import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 11 | +import io.netty.handler.logging.LogLevel; |
| 12 | +import io.netty.handler.logging.LoggingHandler; |
| 13 | + |
| 14 | +/** |
| 15 | + * Created by ipipman on 2022/1/19. |
| 16 | + * |
| 17 | + * @version V1.0 |
| 18 | + * @Package com.ipman.netty.springboot.sample.http |
| 19 | + * @Description: (用一句话描述该文件做什么) |
| 20 | + * @date 2022/1/19 9:09 下午 |
| 21 | + */ |
| 22 | +public class EchoServer { |
| 23 | + |
| 24 | + public static void main(String[] args) { |
| 25 | + // 创建Server端 |
| 26 | + EventLoopGroup workGroup = new NioEventLoopGroup(); |
| 27 | + final EchoServerHandler serverHandler = new EchoServerHandler(); |
| 28 | + try { |
| 29 | + ServerBootstrap b = new ServerBootstrap(); |
| 30 | + b.group(workGroup) |
| 31 | + .channel(NioServerSocketChannel.class) |
| 32 | + .handler(new LoggingHandler(LogLevel.INFO)) |
| 33 | + .childHandler(new ChannelInitializer<SocketChannel>() { |
| 34 | + @Override |
| 35 | + public void initChannel(SocketChannel ch) throws Exception { |
| 36 | + ChannelPipeline p = ch.pipeline(); |
| 37 | + p.addLast(new LoggingHandler(LogLevel.INFO)); |
| 38 | + p.addLast(serverHandler); |
| 39 | + } |
| 40 | + }); |
| 41 | + // 绑定端口 |
| 42 | + ChannelFuture f = b.bind(8090).sync(); |
| 43 | + // 等待连接关闭 |
| 44 | + f.channel().closeFuture().sync(); |
| 45 | + } catch (InterruptedException e) { |
| 46 | + e.printStackTrace(); |
| 47 | + } finally { |
| 48 | + // 关闭所有线程 |
| 49 | + workGroup.shutdownGracefully(); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments