直接上代码:
pom依赖:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.42.Final</version>
</dependency>
服务端:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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 io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
// 创建两个线程组,bossGroup只处理连接请求,workerGroup处理具体的业务
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//按行解码
pipeline.addLast(new LineBasedFrameDecoder(1024));
//将LineBasedFrameDecoder解码出来的数据字解码为字符串
pipeline.addLast(new StringDecoder());
//用于将发送的数据编码
pipeline.addLast(new StringEncoder());
pipeline.addLast(new SimpleServerHandler());
}
});
// 绑定端口,开始接收进来的连接
ChannelFuture future = bootstrap.bind(8080).sync();
System.out.println("Server start listen at 8080 ");
future.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.nio.charset.StandardCharsets;
public class SimpleServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("client msg:" + msg);
byte[] bytes = (msg + "\r\n").getBytes(StandardCharsets.UTF_8);
ctx.channel().writeAndFlush(Unpooled.wrappedBuffer(bytes)).sync();
}
}
客户端:
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class NettyClient {
public static void main(String[] args) throws Exception {
// 创建事件循环组
EventLoopGroup group = new NioEventLoopGroup();
try {
// 创建Bootstrap对象
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new CustomChannelHandler());
}
});
// 连接服务器
ChannelFuture future = bootstrap.connect("localhost", 8080).sync();
System.out.println("Connected to server");
// 从控制台读取输入,并发送给服务器
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
// 发送一行数据,并加上回车换行符
// 将String类型的消息转换为ByteBuf类型的消息
byte[] bytes = (line + "\r\n").getBytes(StandardCharsets.UTF_8);
future.channel().writeAndFlush(Unpooled.wrappedBuffer(bytes)).sync();
}
// 等待连接关闭
future.channel().closeFuture().sync();
} finally {
// 优雅地关闭事件循环组
group.shutdownGracefully();
}
}
}
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.StandardCharsets;
public class CustomChannelHandler extends ChannelInboundHandlerAdapter {
// 处理接收到的消息
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 处理接收到的消息
String line = ((ByteBuf) msg).toString(StandardCharsets.UTF_8);
System.out.println("Received message: " + line);
}
}