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