1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.localecho;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.bootstrap.ServerBootstrap;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.channel.ChannelInitializer;
23 import io.netty.channel.EventLoopGroup;
24 import io.netty.channel.MultiThreadIoEventLoopGroup;
25 import io.netty.channel.local.LocalAddress;
26 import io.netty.channel.local.LocalChannel;
27 import io.netty.channel.local.LocalIoHandler;
28 import io.netty.channel.local.LocalServerChannel;
29 import io.netty.handler.logging.LogLevel;
30 import io.netty.handler.logging.LoggingHandler;
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 MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
44 EventLoopGroup clientGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.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).sync();
81
82
83 Channel ch = cb.connect(addr).sync().channel();
84
85
86 System.out.println("Enter text (quit to end)");
87 ChannelFuture 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.awaitUninterruptibly();
102 }
103 } finally {
104 serverGroup.shutdownGracefully();
105 clientGroup.shutdownGracefully();
106 }
107 }
108 }