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