Netty(一):的入门使用。

Netty的入门基本使用流程代码,不做具体分析。使用版本为Netty 4.x版本。

服务端调用示例:

  绑定端口号为8080端口

 package com.cllover;

 import com.sun.webkit.EventLoop;
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 Server {
public static void main(String[] args) { //接受连接
EventLoopGroup parentEventLoopGroup = new NioEventLoopGroup();
EventLoopGroup childEventLoopGroup = new NioEventLoopGroup(); try {
//入口
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(parentEventLoopGroup,childEventLoopGroup).
channel(NioServerSocketChannel.class).childHandler(new Init());
//绑定运行端口
ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//连接关闭
parentEventLoopGroup.shutdownGracefully();
childEventLoopGroup.shutdownGracefully();
} }
}

Init:初始化类

 package com.cllover;

 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 Init extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("httpServerCode",new HttpServerCodec());
pipeline.addLast("httpServerHandler",new HttpServerHandler()); }
}

HttpServerHandler:自定义服务端处理器

 package com.cllover;

 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 HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> { /*
* 数据处理方法
* */
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) {
ByteBuf byteBuf = Unpooled.copiedBuffer("Hello World!", CharsetUtil.UTF_8);
FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK, byteBuf);

        //加入头信息
fullHttpResponse.headers().set(HttpHeaderNames.ACCEPT_CHARSET, "UTF_8");
fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
ctx.writeAndFlush(fullHttpResponse);
}
}
}

运行方式:

  1. 在本机windows/子系统linux上输入:curl locaclhost:8080

Netty(一):的入门使用。

  2.在浏览器输入localhost:8080

Netty(一):的入门使用。

头信息:

Netty(一):的入门使用。

上一篇:netty学习:UDP服务器与Spring整合


下一篇:remote debug in visual studio