1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.http.websocketx.server;
17
18 import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
19 import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
20 import static org.jboss.netty.handler.codec.http.HttpMethod.*;
21 import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;
22 import static org.jboss.netty.handler.codec.http.HttpVersion.*;
23
24 import org.jboss.netty.buffer.ChannelBuffer;
25 import org.jboss.netty.buffer.ChannelBuffers;
26 import org.jboss.netty.channel.ChannelFuture;
27 import org.jboss.netty.channel.ChannelFutureListener;
28 import org.jboss.netty.channel.ChannelHandlerContext;
29 import org.jboss.netty.channel.ExceptionEvent;
30 import org.jboss.netty.channel.MessageEvent;
31 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
32 import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
33 import org.jboss.netty.handler.codec.http.HttpRequest;
34 import org.jboss.netty.handler.codec.http.HttpResponse;
35 import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
36 import org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame;
37 import org.jboss.netty.handler.codec.http.websocketx.PongWebSocketFrame;
38 import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
39 import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
40 import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
41 import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
42 import org.jboss.netty.logging.InternalLogger;
43 import org.jboss.netty.logging.InternalLoggerFactory;
44 import org.jboss.netty.util.CharsetUtil;
45
46
47
48
49 public class WebSocketServerHandler extends SimpleChannelUpstreamHandler {
50 private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandler.class);
51
52 private static final String WEBSOCKET_PATH = "/websocket";
53
54 private WebSocketServerHandshaker handshaker;
55
56 @Override
57 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
58 Object msg = e.getMessage();
59 if (msg instanceof HttpRequest) {
60 handleHttpRequest(ctx, (HttpRequest) msg);
61 } else if (msg instanceof WebSocketFrame) {
62 handleWebSocketFrame(ctx, (WebSocketFrame) msg);
63 }
64 }
65
66 private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
67
68 if (req.getMethod() != GET) {
69 sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
70 return;
71 }
72
73
74 if (req.getUri().equals("/")) {
75 HttpResponse res = new DefaultHttpResponse(HTTP_1_1, OK);
76
77 ChannelBuffer content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
78
79 res.setHeader(CONTENT_TYPE, "text/html; charset=UTF-8");
80 setContentLength(res, content.readableBytes());
81
82 res.setContent(content);
83 sendHttpResponse(ctx, req, res);
84 return;
85 } else if (req.getUri().equals("/favicon.ico")) {
86 HttpResponse res = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
87 sendHttpResponse(ctx, req, res);
88 return;
89 }
90
91
92 WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
93 getWebSocketLocation(req), null, false);
94 handshaker = wsFactory.newHandshaker(req);
95 if (handshaker == null) {
96 wsFactory.sendUnsupportedWebSocketVersionResponse(ctx.getChannel());
97 } else {
98 handshaker.handshake(ctx.getChannel(), req).addListener(WebSocketServerHandshaker.HANDSHAKE_LISTENER);
99 }
100 }
101
102 private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
103
104
105 if (frame instanceof CloseWebSocketFrame) {
106 handshaker.close(ctx.getChannel(), (CloseWebSocketFrame) frame);
107 return;
108 } else if (frame instanceof PingWebSocketFrame) {
109 ctx.getChannel().write(new PongWebSocketFrame(frame.getBinaryData()));
110 return;
111 } else if (!(frame instanceof TextWebSocketFrame)) {
112 throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
113 .getName()));
114 }
115
116
117 String request = ((TextWebSocketFrame) frame).getText();
118 if (logger.isDebugEnabled()) {
119 logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request));
120 }
121 ctx.getChannel().write(new TextWebSocketFrame(request.toUpperCase()));
122 }
123
124 private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
125
126 if (res.getStatus().getCode() != 200) {
127 res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
128 setContentLength(res, res.getContent().readableBytes());
129 }
130
131
132 ChannelFuture f = ctx.getChannel().write(res);
133 if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
134 f.addListener(ChannelFutureListener.CLOSE);
135 }
136 }
137
138 @Override
139 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
140 e.getCause().printStackTrace();
141 e.getChannel().close();
142 }
143
144 private static String getWebSocketLocation(HttpRequest req) {
145 return "ws://" + req.getHeader(HOST) + WEBSOCKET_PATH;
146 }
147 }