添加依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.39.Final</version>
</dependency>
服务端
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 lombok.extern.slf4j.Slf4j;
@Slf4j
public class HelloServer {
public static void main(String[] args) {
// 创建启动器
new ServerBootstrap()
// 创建EventLoop事件监听处理组
.group(new NioEventLoopGroup())
// 设置ServerSocketChannel的实现NioServerSocketChannel
.channel(NioServerSocketChannel.class)
// 设置处理器
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// 添加处理工序 处理stringBuf为字符串
ch.pipeline().addLast(new StringDecoder());
// 自定义处理器
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
// 监听读时间
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 打印上一步转换好的字符串
log.debug((String) msg);
}
});
}
}).bind(8080); // 绑定的监听端口
}
}
客户端
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
public class HelloClient {
public static void main(String[] args) throws InterruptedException {
//1 启动类
new Bootstrap()
// 2.添加EventLoop
.group(new NioEventLoopGroup())
// 3.选择客服端channel实现
.channel(NioSocketChannel.class)
// 4 添加处理器
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
}
// 连接地址
}).connect(new InetSocketAddress("127.0.0.1", 8080))
.sync()
.channel()
.writeAndFlush("hello world");
}
}
服务端成功接收来自客户端的请求
来源 : 黑马程序员Netty全套教程