Netty 是一款异步的、基于事件驱动的网络应用程序框架,用以快速开发高性能、高可靠性的网络 IO 程序。
引入依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.77.Final</version>
</dependency>
服务端
服务端监听 8081 端口
package com.example.demo.nettydemo;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import java.util.Date;
public class HelloWorldServer {
public static void main(String[] args) {
// 创建服务端启动引导器
ServerBootstrap bootstrap = new ServerBootstrap();
// 配置线程模型
bootstrap.group(new NioEventLoopGroup());
// 指定服务端的 IO 模型
bootstrap.channel(NioServerSocketChannel.class);
// 定义处理器 Handler
bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel channel) throws Exception {
// 解码
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel() + ",hello world");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(new Date() + ":" + msg);
}
});
}
});
// 绑定 8081 端口
bootstrap.bind(8081);
}
}
客户端
客户端每隔5秒给服务端发送一条信息
package com.example.demo.nettydemo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.util.concurrent.TimeUnit;
public class HelloWorldClient {
public static void main(String[] args) throws InterruptedException {
// 客户端引导器
Bootstrap bootstrap = new Bootstrap();
// 配置线程组
bootstrap.group(new NioEventLoopGroup());
// 指定 IO 类型为 NIO
bootstrap.channel(NioSocketChannel.class);
// 配置 IO 处理器
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
}
});
// 建立连接
Channel channel = bootstrap.connect("127.0.0.1",8081).channel();
// 发送消息
while (true) {
channel.writeAndFlush("hello world..");
TimeUnit.SECONDS.sleep(5);
}
}
}
参考文章