packagecn.rainwer.nettywebsocket.Server;importio.netty.bootstrap.ServerBootstrap;importio.netty.channel.ChannelFuture;importio.netty.channel.ChannelInitializer;importio.netty.channel.EventLoopGroup;importio.netty.channel.nio.NioEventLoopGroup;importio.netty.channel.socket.SocketChannel;importio.netty.channel.socket.nio.NioServerSocketChannel;importio.netty.handler.codec.http.HttpObjectAggregator;importio.netty.handler.codec.http.HttpServerCodec;importio.netty.handler.codec.http.HttpServerExpectContinueHandler;publicclassNettyHttpServer{publicstaticvoidmain(String[] args){EventLoopGroup bossGroup =newNioEventLoopGroup(1);EventLoopGroup workerGroup =newNioEventLoopGroup();ChannelFuture f =null;try{//ServerBootstrap负责初始化netty服务器,并且开始监听端口的socket请求ServerBootstrap b =newServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(newChannelInitializer<SocketChannel>(){@OverrideprotectedvoidinitChannel(SocketChannel socketChannel)throwsException{// 为监听客户端read/write事件的Channel添加用户自定义的ChannelHandlersocketChannel.pipeline()// .addLast("decoder", new HttpRequestDecoder())// .addLast("encoder", new HttpResponseEncoder()).addLast(newHttpServerCodec()).addLast(newHttpServerExpectContinueHandler()).addLast("aggregator",newHttpObjectAggregator(512*1024)).addLast(newNettyWebSocketConnectHandler2());}});f = b.bind(9996).sync();System.out.println("======NettyServer启动成功!!!=========");// f.channel().closeFuture().sync();}catch(Exception e){e.printStackTrace();}finally{if(f !=null&& f.isSuccess()){System.out.println("Netty server listening on port "+" and ready for connections...");}else{System.out.println("Netty server start up Error!");}}}}
packagecn.rainwer.nettywebsocket.Server;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelHandler;importio.netty.channel.ChannelHandlerContext;importio.netty.channel.SimpleChannelInboundHandler;importio.netty.handler.codec.http.*;importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Component;importjava.net.InetAddress;importjava.nio.charset.StandardCharsets;@Slf4j@ChannelHandler.Sharable@ComponentpublicclassNettyWebSocketConnectHandler2extendsSimpleChannelInboundHandler<Object>{@OverridepublicvoidchannelRead(ChannelHandlerContext channelHandlerContext,Object msg)throwsException{if(msg instanceofFullHttpRequest){log.info("准备提取token");//转化为http请求FullHttpRequest request =(FullHttpRequest) msg;//拿到请求地址String uri = request.uri();System.out.println(uri);//判断是不是websocket请求,如果是拿出我们传递的参数(我的是token)channelHandlerContext.channel().writeAndFlush("Welcome to "+InetAddress.getLocalHost().getHostName()+" service!\n");FullHttpResponse fullHttpResponse =newDefaultFullHttpResponse(request.protocolVersion(),HttpResponseStatus.OK,Unpooled.wrappedBuffer(uri.getBytes(StandardCharsets.UTF_8)));fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,HttpHeaderValues.TEXT_PLAIN).set(HttpHeaderNames.CONTENT_LENGTH, fullHttpResponse.content().readableBytes());channelHandlerContext.writeAndFlush(fullHttpResponse);}else{}}}