mirror of
https://codeup.aliyun.com/67c68d4e484ca2f0a13ac3c1/ydc/jsowell-charger-web.git
synced 2026-04-21 11:35:12 +08:00
52 lines
1.5 KiB
Java
52 lines
1.5 KiB
Java
package com.jsowell.pile.rpc;
|
|
|
|
import io.netty.bootstrap.Bootstrap;
|
|
import io.netty.channel.*;
|
|
import io.netty.channel.nio.NioEventLoopGroup;
|
|
import io.netty.channel.socket.nio.NioSocketChannel;
|
|
|
|
public class RpcClient {
|
|
|
|
public Channel connect(String host, Integer port) {
|
|
EventLoopGroup worker = new NioEventLoopGroup();
|
|
Channel channel = null;
|
|
|
|
try {
|
|
Bootstrap bootstrap = new Bootstrap();
|
|
|
|
bootstrap.group(worker)
|
|
.channel(NioSocketChannel.class)
|
|
.option(ChannelOption.AUTO_READ, true)
|
|
.handler(new ClientChannelInitializer());
|
|
|
|
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
|
|
|
|
System.out.println("客户端启动");
|
|
|
|
channel = channelFuture.channel();
|
|
|
|
// 添加关闭监听器
|
|
channel.closeFuture().addListener(new ChannelFutureListener() {
|
|
@Override
|
|
public void operationComplete(ChannelFuture channelFuture) throws Exception {
|
|
System.out.println("关闭客户端");
|
|
worker.shutdownGracefully();
|
|
}
|
|
});
|
|
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
|
|
if(channel == null || !channel.isActive()) {
|
|
worker.shutdownGracefully();
|
|
} else {
|
|
channel.close();
|
|
}
|
|
|
|
}
|
|
|
|
return channel;
|
|
}
|
|
|
|
|
|
} |