1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.example.localecho;
17
18 import io.netty5.bootstrap.Bootstrap;
19 import io.netty5.bootstrap.ServerBootstrap;
20 import io.netty5.channel.Channel;
21 import io.netty5.channel.ChannelInitializer;
22 import io.netty5.channel.EventLoopGroup;
23 import io.netty5.channel.MultithreadEventLoopGroup;
24 import io.netty5.channel.local.LocalAddress;
25 import io.netty5.channel.local.LocalChannel;
26 import io.netty5.channel.local.LocalHandler;
27 import io.netty5.channel.local.LocalServerChannel;
28 import io.netty5.handler.logging.LogLevel;
29 import io.netty5.handler.logging.LoggingHandler;
30 import io.netty5.util.concurrent.Future;
31
32 import java.io.BufferedReader;
33 import java.io.InputStreamReader;
34
35 public final class LocalEcho {
36
37 static final String PORT = System.getProperty("port", "test_port");
38
39 public static void main(String[] args) throws Exception {
40
41 final LocalAddress addr = new LocalAddress(PORT);
42
43 EventLoopGroup serverGroup = new MultithreadEventLoopGroup(LocalHandler.newFactory());
44 EventLoopGroup clientGroup = new MultithreadEventLoopGroup(LocalHandler.newFactory());
45 try {
46
47
48
49 ServerBootstrap sb = new ServerBootstrap();
50 sb.group(serverGroup)
51 .channel(LocalServerChannel.class)
52 .handler(new ChannelInitializer<LocalServerChannel>() {
53 @Override
54 public void initChannel(LocalServerChannel ch) throws Exception {
55 ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
56 }
57 })
58 .childHandler(new ChannelInitializer<LocalChannel>() {
59 @Override
60 public void initChannel(LocalChannel ch) throws Exception {
61 ch.pipeline().addLast(
62 new LoggingHandler(LogLevel.INFO),
63 new LocalEchoServerHandler());
64 }
65 });
66
67 Bootstrap cb = new Bootstrap();
68 cb.group(clientGroup)
69 .channel(LocalChannel.class)
70 .handler(new ChannelInitializer<LocalChannel>() {
71 @Override
72 public void initChannel(LocalChannel ch) throws Exception {
73 ch.pipeline().addLast(
74 new LoggingHandler(LogLevel.INFO),
75 new LocalEchoClientHandler());
76 }
77 });
78
79
80 sb.bind(addr).asStage().sync();
81
82
83 Channel ch = cb.connect(addr).asStage().get();
84
85
86 System.out.println("Enter text (quit to end)");
87 Future<Void> lastWriteFuture = null;
88 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
89 for (;;) {
90 String line = in.readLine();
91 if (line == null || "quit".equalsIgnoreCase(line)) {
92 break;
93 }
94
95
96 lastWriteFuture = ch.writeAndFlush(line);
97 }
98
99
100 if (lastWriteFuture != null) {
101 lastWriteFuture.asStage().await();
102 }
103 } finally {
104 serverGroup.shutdownGracefully();
105 clientGroup.shutdownGracefully();
106 }
107 }
108 }