Netty基本使用流程代码
生活随笔
收集整理的這篇文章主要介紹了
Netty基本使用流程代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面的代碼是Netty基本的使用流程代碼,幾乎Netty的使用都是使用下面的流程,這是一個HttpServer的簡單應用,它將返回"Hello world"給客戶端,復制修改以快速構建Netty應用(Netty版本4.1.10)。
TestServer.java
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel;public class TestServer {public static void main(String[] args) {//兩個事件循環組,都是死循環,bossGroup接收客戶端EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try{ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new TestServerInitializer());ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();channelFuture.channel().closeFuture().sync();}catch (Exception e){System.out.println(e.fillInStackTrace());}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}} }TestServerInitializer.java
import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpServerCodec;public class TestServerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();pipeline.addLast("httpServerCodec", new HttpServerCodec());pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler());} }TestHttpServerHandler.java
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil;public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {//讀取客戶端請求,并返回響應給客戶端@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {if(httpObject instanceof HttpRequest){ByteBuf content = Unpooled.copiedBuffer("Hello world", CharsetUtil.UTF_8);FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, content);response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());channelHandlerContext.writeAndFlush(response);}} }驗證:
$ curl 'http://localhost:8899' Hello world總結
以上是生活随笔為你收集整理的Netty基本使用流程代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring - IOC常用标签
- 下一篇: Spring IOC示例代码