一、创建项目
netty项目可以通过maven创建,需要用到io.netty.netty-all的jar包
pom.xml中添加依赖:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.32.Final</version>
</dependency>
编写一个简单的服务器实现简单地将客户端的内容返回回去
EchoServer.java和EchoServerHandller.java:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;
public class EchoServer {
private final int port;
public EchoServer(int prot) {
this.port = prot;
}
public void start() throws Exception {
final EchoServerHandler serverHandler = new EchoServerHandler();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
// 使用NIO的Channel
.channel(NioServerSocketChannel.class)
// 绑定到本地地址的某个端口
.localAddress(new InetSocketAddress(port))
// 为每个channel的pipe line添加handler
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel socketChannel) throws Exception {
// 将handler添加到pipeline中
socketChannel.pipeline().addLast(serverHandler);
}
});
// 绑定,获取future回调
ChannelFuture future = bootstrap.bind().sync();
future.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
new EchoServer(9999).start();
}
}
public class EchoServerHandler extends ChannelInboundHa