1、maven 依赖
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.65.Final</version> </dependency>
2、Server 端
public class HttpServer { private int port; public HttpServer(int port) { this.port = port; } public void bind() { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new NettyServerChannelInitializer()) .option(ChannelOption.SO_BACKLOG, 500) .childOption(ChannelOption.SO_KEEPALIVE, true); // 绑定端口,开始接收进来的连接 ChannelFuture future = bootstrap.bind(port).sync(); //关闭channel和块,直到它被关闭 future.channel().closeFuture().sync(); } catch (Exception e) { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
NettyServerChannelInitializer
public class NettyServerChannelInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast("socketChoose",new SocketChooseHandle()); channel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8)); channel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8)); channel.pipeline().addLast("commonhandler",new WebSocketHandler()); } }
SocketChooseHandle
public class SocketChooseHandle extends ByteToMessageDecoder { /** 默认暗号长度为23 */ private static final int MAX_LENGTH = 23; /** WebSocket握手的协议前缀 */ private static final String WEBSOCKET_PREFIX = "GET /"; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List&