Repository navigation
Expand file tree
/
Copy pathNettyClient.java
More file actions
82 lines (70 loc) · 2.78 KB
/
Copy pathNettyClient.java
File metadata and controls
82 lines (70 loc) · 2.78 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
package netty;
import static netty.NettyConfig.*;
import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.channel.Channel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Created by zhengyong on 17/5/27.
*/
public class NettyClient {
private static Channel channel;
public static void main(String[] args) throws Exception {
connect(HOST, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("start client success, please enter message send to server.");
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
write(line);
}
}
private static void write(String msg) throws Exception {
if (channel == null) {
throw new NullPointerException("channel must be not null");
}
// Sends the received line to the server.
ChannelFuture future = channel.writeAndFlush(msg);
// If user typed the 'bye' command, wait until the server closes
// the connection.
if ("bye".equals(msg.toLowerCase())) {
channel.closeFuture().sync();
return;
}
if (future != null) {
future.sync();
}
}
private static Channel connect(String host, int port) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
// p.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
// p.addLast(new ObjectEncoder());
p.addLast(new CustomHessianDecoder());
p.addLast(new CustomHessianEncoder());
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new NettyClientHandler());
}
});
bootstrap.validate();
channel = bootstrap.connect(host, port).sync().channel();
return channel;
}
}