Netty入门Demo

1. 添加依赖

1
2
3
4
5
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.34.Final</version>
</dependency>

2. 编写消息接收处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class NettyServerHandler extends ChannelInboundHandlerAdapter{

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf in = (ByteBuf)msg;
System.out.println(ctx.name()+"发送:"+in.toString(io.netty.util.CharsetUtil.US_ASCII));
} finally {
//释放传递给处理程序的引用计数对象
ReferenceCountUtil.release(msg);
}
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}

3. 编写服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class NettyServerDemo {
private int port;

public NettyServerDemo(int port) {
this.port = port;
}

public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);

//绑定端口,并等待连接
ChannelFuture f = b.bind(port).sync();

// 关闭服务
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}

public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new NettyServerDemo(port).run();
}
}

4. 测试

  1. 启动NettyServerDemo
  2. 命令行中输入: telnet localhost 8080
    如果找不到Telnet命令,说明Telnet客户端没有打开,在控制面板中—> 程序 ——> 打开或关闭Windows功能

    当输入信息后,服务器端会收到点击的键,并输出出来
-------------本文结束感谢您的阅读-------------