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