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.util.concurrent.Executor;
19
20 import org.jboss.netty.channel.ChannelDownstreamHandler;
21 import org.jboss.netty.channel.ChannelEvent;
22 import org.jboss.netty.channel.ChannelHandlerContext;
23 import org.jboss.netty.channel.ChannelPipeline;
24 import org.jboss.netty.channel.ChannelPipelineFactory;
25 import org.jboss.netty.channel.ChannelUpstreamHandler;
26 import org.jboss.netty.channel.Channels;
27 import org.jboss.netty.channel.MessageEvent;
28 import org.jboss.netty.handler.codec.string.StringDecoder;
29 import org.jboss.netty.handler.codec.string.StringEncoder;
30 import org.jboss.netty.handler.execution.ExecutionHandler;
31
32 public class LocalServerPipelineFactory implements ChannelPipelineFactory {
33
34 private final ExecutionHandler executionHandler;
35
36 public LocalServerPipelineFactory(Executor eventExecutor) {
37 executionHandler = new ExecutionHandler(eventExecutor);
38 }
39
40 public ChannelPipeline getPipeline() throws Exception {
41 final ChannelPipeline pipeline = Channels.pipeline();
42 pipeline.addLast("decoder", new StringDecoder());
43 pipeline.addLast("encoder", new StringEncoder());
44 pipeline.addLast("executor", executionHandler);
45 pipeline.addLast("handler", new EchoCloseServerHandler());
46 return pipeline;
47 }
48
49 static class EchoCloseServerHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler {
50 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
51 throws Exception {
52 if (e instanceof MessageEvent) {
53 final MessageEvent evt = (MessageEvent) e;
54 String msg = (String) evt.getMessage();
55 if (msg.equalsIgnoreCase("quit")) {
56 Channels.close(e.getChannel());
57 return;
58 }
59 }
60 ctx.sendUpstream(e);
61 }
62
63 public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) {
64 if (e instanceof MessageEvent) {
65 final MessageEvent evt = (MessageEvent) e;
66 String msg = (String) evt.getMessage();
67 if (msg.equalsIgnoreCase("quit")) {
68 Channels.close(e.getChannel());
69 return;
70 }
71 System.err.println("SERVER:" + msg);
72
73 Channels.write(e.getChannel(), msg);
74 }
75 ctx.sendDownstream(e);
76 }
77 }
78 }