来来来写一个Netty “hello world”。
首先看一下API
netty 官方API: http://netty.io/4.1/api/index.html
一、添加maven依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
二、创建服务端
package netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class HttpServer {
private final int port;
public HttpServer(int port) {
this.port = port;
}
public static void main(String[] args){
int port = 20008;
try {
new HttpServer(port).start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void start() throws Exception {
ServerBootstrap b = new ServerBootstrap();
NioEventLoopGroup group = new NioEventLoopGroup();
b.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch){
System.out.println("======initChannel ch:" + ch);
// 基于HTTP协议的。需要注意这边设置的要和handler端的类型一样
// ch.pipeline()
// .addLast("decoder", new HttpRequestDecoder()) // 1
// .addLast("encoder", new HttpResponseEncoder()) // 2
.addLast("aggregator", new HttpObjectAggregator(512 * 1024)) // 3
// .addLast("aggregator", new HttpObjectAggregator(65536))
// .addLast("http-codec", new HttpServerCodec())
// .addLast(new HttpHandler()); // 4
// 无限制默认
ch.pipeline().addLast(new HttpHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // determining the number of connections queued
.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
b.bind(port).sync();
}
}
三、创建handler
package netty;
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.AsciiString;
public class HttpHandler extends SimpleChannelInboundHandler<Object> { // 1
private AsciiString contentType = HttpHeaderValues.TEXT_PLAIN;
// 接受数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
System.out.println("class:" + msg.getClass().getName());
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer("test".getBytes())); // 2
HttpHeaders heads = response.headers();
heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 3
heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.write(response);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelReadComplete");
super.channelReadComplete(ctx);
ctx.flush(); // 4
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("exceptionCaught");
if (null != cause) cause.printStackTrace();
if (null != ctx) ctx.close();
}
}
三、运行服务端,然后ping一下对应的接口,观察控制台打印。
一个netty hello world就OK了。