1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.local;
17
18 import java.io.BufferedReader;
19 import java.io.IOException;
20 import java.io.InputStreamReader;
21
22 import org.jboss.netty.bootstrap.ClientBootstrap;
23 import org.jboss.netty.bootstrap.ServerBootstrap;
24 import org.jboss.netty.channel.ChannelFuture;
25 import org.jboss.netty.channel.ChannelPipeline;
26 import org.jboss.netty.channel.ChannelPipelineFactory;
27 import org.jboss.netty.channel.Channels;
28 import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory;
29 import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory;
30 import org.jboss.netty.channel.local.LocalAddress;
31 import org.jboss.netty.example.echo.EchoServerHandler;
32 import org.jboss.netty.handler.codec.string.StringDecoder;
33 import org.jboss.netty.handler.codec.string.StringEncoder;
34 import org.jboss.netty.handler.logging.LoggingHandler;
35 import org.jboss.netty.logging.InternalLogLevel;
36
37 public class LocalExample {
38
39 private final String port;
40
41 public LocalExample(String port) {
42 this.port = port;
43 }
44
45 public void run() throws IOException {
46
47 LocalAddress socketAddress = new LocalAddress(port);
48
49
50 ServerBootstrap sb = new ServerBootstrap(
51 new DefaultLocalServerChannelFactory());
52
53
54 EchoServerHandler handler = new EchoServerHandler();
55 sb.getPipeline().addLast("handler", handler);
56
57
58 sb.bind(socketAddress);
59
60
61 ClientBootstrap cb = new ClientBootstrap(
62 new DefaultLocalClientChannelFactory());
63
64
65 cb.setPipelineFactory(new ChannelPipelineFactory() {
66 public ChannelPipeline getPipeline() throws Exception {
67 return Channels.pipeline(
68 new StringDecoder(),
69 new StringEncoder(),
70 new LoggingHandler(InternalLogLevel.INFO));
71 }
72 });
73
74
75 ChannelFuture channelFuture = cb.connect(socketAddress);
76 channelFuture.awaitUninterruptibly();
77
78
79 System.out.println("Enter text (quit to end)");
80 ChannelFuture lastWriteFuture = null;
81 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
82 for (; ;) {
83 String line = in.readLine();
84 if (line == null || "quit".equalsIgnoreCase(line)) {
85 break;
86 }
87
88
89 lastWriteFuture = channelFuture.getChannel().write(line);
90 }
91
92
93 if (lastWriteFuture != null) {
94 lastWriteFuture.awaitUninterruptibly();
95 }
96 channelFuture.getChannel().close();
97
98
99 channelFuture.getChannel().getCloseFuture().awaitUninterruptibly();
100
101
102 cb.releaseExternalResources();
103 sb.releaseExternalResources();
104 }
105
106 public static void main(String[] args) throws Exception {
107 new LocalExample("1").run();
108 }
109 }