-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathNettyClient.java
More file actions
84 lines (71 loc) · 2.68 KB
/
NettyClient.java
File metadata and controls
84 lines (71 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package top.guoziyang.mydb.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
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.NioSocketChannel;
import top.guoziyang.mydb.transport.DecoderHandler;
import top.guoziyang.mydb.transport.EncoderHandler;
import top.guoziyang.mydb.transport.Package;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* Netty客户端
* 作者:RioAngele
* 时间:2023.5.23
*/
public final class NettyClient {
private final Bootstrap bootstrap;
private final EventLoopGroup eventLoopGroup;
public Channel channel;
public static CompletableFuture<Package> resultFuture;
public NettyClient() throws InterruptedException {
CompletableFuture<byte[]> resultFuture= new CompletableFuture<>();
eventLoopGroup = new NioEventLoopGroup();
bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new EncoderHandler())
.addLast(new DecoderHandler())
.addLast(new NettyClientHandler());
}
});
channel=bootstrap.connect("127.0.0.1",7777).sync().channel();
}
public byte[] execute(byte[] sh) throws Exception {
resultFuture=new CompletableFuture<Package>();
Package pkg=new Package(sh,null);
if (channel.isActive()) {
channel.writeAndFlush(pkg).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
System.out.println("success to send");
} else {
System.out.println("fail to send");
future.channel().close();
}
});
} else {
throw new IllegalStateException();
}
Package resPkg=null;
while(!resultFuture.isDone()){
}
resPkg=resultFuture.get();
if(resPkg.getErr() != null) {
throw resPkg.getErr();
}
return resPkg.getData();
}
public void close() {
eventLoopGroup.shutdownGracefully();
}
}