Demo/src/main/java/com/example/demo/Service/nettyClient.java
2024-10-27 19:22:40 +08:00

53 lines
1.9 KiB
Java

package com.example.demo.Service;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.stereotype.Component;
@Component
public class nettyClient {
private final String host = "127.0.0.1"; // 目标服务器地址
private final int port = 8081; // 目标服务器端口
public void start() throws InterruptedException {
// 1. 创建 EventLoopGroup 用于管理客户端的 NIO 线程
EventLoopGroup group = new NioEventLoopGroup();
try {
// 2. Bootstrap 用于创建客户端
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group) // 指定线程组
.channel(NioSocketChannel.class) // 指定使用 NIO 传输的Channel
//.option(ChannelOption.SO_KEEPALIVE, true) // 保持长连接
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
// 3. 配置客户端的 ChannelHandler
ch.pipeline().addLast(new nettyClientHandler());
}
});
// 4. 连接服务器
ChannelFuture future = bootstrap.connect(host, port).sync();
// 5. 向服务器发送消息
//future.channel().writeAndFlush("Hello, Netty Server!");
// 6. 等待连接关闭
future.channel().closeFuture().sync();
System.out.println("aaa");
} finally {
// 7. 关闭线程组
group.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
new nettyClient().start();
}
}