Netty Example
Netty Server
public class NettyServer {
private final static int port = 8080;
public static void main(String[] args) {
// 用来接收进来的连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
// 用来处理已经被接收的连接,一旦bossGroup接收到连接,就会把连接信息注册到workerGroup上
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
// nio服务的启动类
ServerBootstrap sbs = new ServerBootstrap();
// 配置nio服务参数
sbs.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // 说明一个新的Channel如何接收进来的连接
.option(ChannelOption.SO_BACKLOG, 128) // tcp最大缓存链接个数
.childOption(ChannelOption.SO_KEEPALIVE, true) //保持连接
.handler(new LoggingHandler(LogLevel.INFO)) // 打印日志级别
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new ServerHandler());
}
});
System.err.println("server 开启--------------");
// 绑定端口并添加监听器
ChannelFuture cf = sbs.bind(port).addListener(future -> {
if (future.isSuccess()) {
System.out.println("Server bound to port " + port);
} else {
System.err.println("Failed to bind to port " + port);
System.err.println("Failed to bind to port " + future.cause().getMessage());
}
});
cf.channel().closeFuture().sync();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class ServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("Received: " + msg);
ctx.writeAndFlush("Hello from server");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//cause.printStackTrace();
System.out.println(cause.getMessage());
ctx.close();
}
}
#Netty Client
public class NettyClient {
private final String host;
private final int port;
public NettyClient(String host, int port) {
this.host = host;
this.port = port;
}
public void start() {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) // 禁用 Nagle 算法以减小延迟
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) // 连接超时设置为 5 秒
.handler(new LoggingHandler(LogLevel.INFO)).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new ClientHandler());
}
});
// 连接到服务器
ChannelFuture f = b.connect(host, port).sync();
// 发送消息到服务器并等待消息发送完成
ChannelFuture sendFuture = f.channel().writeAndFlush("Hello from client");
// 添加监听器以在消息发送完成后关闭连接
sendFuture.addListener((ChannelFuture future) -> {
if (future.isSuccess()) {
System.out.println("Message sent successfully, closing connection.");
} else {
System.err.println("Message could not be sent.");
System.err.println("Message could not be sent." + future.cause().getMessage());
}
// 关闭连接
f.channel().close();
});
// 等待直到连接关闭
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) {
String host = "localhost";
int port = 8080;
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
new NettyClient(host, port).start();
}
}).start();
}
}
}
public class ClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("Received: " + msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//cause.printStackTrace();
System.out.println(cause.getMessage());
ctx.close();
}
}