View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.example.http.websocketx.server;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.Unpooled;
20  import io.netty.channel.ChannelFuture;
21  import io.netty.channel.ChannelFutureListener;
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.channel.ChannelPipeline;
24  import io.netty.channel.SimpleChannelInboundHandler;
25  import io.netty.handler.codec.http.DefaultFullHttpResponse;
26  import io.netty.handler.codec.http.FullHttpRequest;
27  import io.netty.handler.codec.http.FullHttpResponse;
28  import io.netty.handler.codec.http.HttpHeaderNames;
29  import io.netty.handler.codec.http.HttpRequest;
30  import io.netty.handler.codec.http.HttpUtil;
31  import io.netty.handler.ssl.SslHandler;
32  import io.netty.util.CharsetUtil;
33  
34  import static io.netty.handler.codec.http.HttpMethod.GET;
35  import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
36  import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
37  import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
38  import static io.netty.handler.codec.http.HttpResponseStatus.OK;
39  import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
40  
41  /**
42   * Outputs index page content.
43   */
44  public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
45  
46      private final String websocketPath;
47  
48      public WebSocketIndexPageHandler(String websocketPath) {
49          this.websocketPath = websocketPath;
50      }
51  
52      @Override
53      protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
54          // Handle a bad request.
55          if (!req.decoderResult().isSuccess()) {
56              sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
57              return;
58          }
59  
60          // Allow only GET methods.
61          if (req.method() != GET) {
62              sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
63              return;
64          }
65  
66          // Send the index page
67          if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) {
68              String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
69              ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation);
70              FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
71  
72              res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
73              HttpUtil.setContentLength(res, content.readableBytes());
74  
75              sendHttpResponse(ctx, req, res);
76          } else {
77              sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
78          }
79      }
80  
81      @Override
82      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
83          cause.printStackTrace();
84          ctx.close();
85      }
86  
87      private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
88          // Generate an error page if response getStatus code is not OK (200).
89          if (res.status().code() != 200) {
90              ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
91              res.content().writeBytes(buf);
92              buf.release();
93              HttpUtil.setContentLength(res, res.content().readableBytes());
94          }
95  
96          // Send the response and close the connection if necessary.
97          ChannelFuture f = ctx.channel().writeAndFlush(res);
98          if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
99              f.addListener(ChannelFutureListener.CLOSE);
100         }
101     }
102 
103     private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
104         String protocol = "ws";
105         if (cp.get(SslHandler.class) != null) {
106             // SSL in use so use Secure WebSockets
107             protocol = "wss";
108         }
109         return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
110     }
111 }