private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) {
// Allow only GET methods.
if (req.getMethod() != GET) {
sendHttpResponse(
ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Serve the WebSocket handshake request.
if (req.getUri().equals(WEBSOCKET_PATH) &&
Values.UPGRADE.equalsIgnoreCase(req.getHeader(CONNECTION)) &&
WEBSOCKET.equalsIgnoreCase(req.getHeader(Names.UPGRADE))) {
// Create the WebSocket handshake response.
HttpResponse res = new DefaultHttpResponse(
HTTP_1_1,
new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
res.addHeader(Names.UPGRADE, WEBSOCKET);
res.addHeader(CONNECTION, Values.UPGRADE);
res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
res.addHeader(WEBSOCKET_LOCATION, getWebSocketLocation(req));
String protocol = req.getHeader(WEBSOCKET_PROTOCOL);
if (protocol != null) {
res.addHeader(WEBSOCKET_PROTOCOL, protocol);
}
// Upgrade the connection and send the handshake response.
ChannelPipeline p = ctx.getChannel().getPipeline();
p.remove("aggregator");
p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder());
ctx.getChannel().write(res);
p.replace("encoder", "wsencoder", new WebSocketFrameEncoder());
ctx.getChannel().write(new DefaultWebSocketFrame("Welcome!"));
return;
}
// Send an error page otherwise.
sendHttpResponse(
ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
}