Example usage for io.netty.handler.codec.http.websocketx WebSocketServerHandshakerFactory sendUnsupportedVersionResponse

List of usage examples for io.netty.handler.codec.http.websocketx WebSocketServerHandshakerFactory sendUnsupportedVersionResponse

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.websocketx WebSocketServerHandshakerFactory sendUnsupportedVersionResponse.

Prototype

public static ChannelFuture sendUnsupportedVersionResponse(Channel channel) 

Source Link

Document

Return that we need cannot not support the web socket version

Usage

From source file:app.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from   w w  w  . j a  v  a  2 s .  co  m
    }

    // Allow only GET methods.
    if (req.method() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true, 5 * 1024 * 1024);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
        channels.add(ctx.channel());
    }
}

From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;/*from w w  w . jav a  2  s .com*/
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = ServerIndexPageWebSocket.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaders.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:chapter10.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {

    // HTTP?HTTP/*from  w w w. j av  a 2s .c o  m*/
    if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;
    }

    // ??
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            "ws://localhost:8080/websocket", null, false);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:cn.npt.net.websocket.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//w w w . j  av  a  2s  . c  o  m
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaders.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:co.paralleluniverse.comsat.webactors.netty.WebActorHandler.java

License:Open Source License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req)
        throws SuspendExecution, InterruptedException {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpError(ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), BAD_REQUEST));
        return;/*from  w  w w.  j ava 2  s  .com*/
    }

    final String uri = req.getUri();

    final Context actorCtx = contextProvider.get(req);
    assert actorCtx != null;
    final String sessionId = actorCtx.getId();
    assert sessionId != null;

    final ReentrantLock lock = actorCtx.getLock();
    assert lock != null;

    lock.lock();

    try {
        final ActorRef<? extends WebMessage> userActorRef = actorCtx.getWebActor();
        ActorImpl internalActor = (ActorImpl) actorCtx.getAttachments().get(ACTOR_KEY);

        if (userActorRef != null) {
            if (actorCtx.handlesWithWebSocket(uri)) {
                if (internalActor == null || !(internalActor instanceof WebSocketActorAdapter)) {
                    //noinspection unchecked
                    webSocketActor = new WebSocketActorAdapter(ctx,
                            (ActorRef<? super WebMessage>) userActorRef);
                    addActorToContextAndUnlock(actorCtx, webSocketActor, lock);
                }
                // Handshake
                final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(uri,
                        null, true);
                handshaker = wsFactory.newHandshaker(req);
                if (handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                } else {
                    @SuppressWarnings("unchecked")
                    final ActorRef<WebMessage> userActorRef0 = (ActorRef<WebMessage>) webSocketActor.userActor;
                    handshaker.handshake(ctx.channel(), req)
                            .addListener(new GenericFutureListener<ChannelFuture>() {
                                @Override
                                @Suspendable
                                public void operationComplete(ChannelFuture future) throws Exception {
                                    userActorRef0.send(
                                            new WebSocketOpened(WebActorHandler.this.webSocketActor.ref()));
                                }
                            });
                }
                return;
            } else if (actorCtx.handlesWithHttp(uri)) {
                if (internalActor == null || !(internalActor instanceof HttpActorAdapter)) {
                    //noinspection unchecked
                    internalActor = new HttpActorAdapter((ActorRef<HttpRequest>) userActorRef, actorCtx,
                            httpResponseEncoderName);
                    addActorToContextAndUnlock(actorCtx, internalActor, lock);
                }
                //noinspection unchecked
                ((HttpActorAdapter) internalActor)
                        .handleRequest(new HttpRequestWrapper(internalActor.ref(), ctx, req, sessionId));
                return;
            }
        }
    } finally {
        if (lock.isHeldByCurrentStrand() && lock.isLocked())
            lock.unlock();
    }

    sendHttpError(ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), NOT_FOUND));
}

From source file:com.chiorichan.http.HttpHandler.java

License:Mozilla Public License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    Timings.start(this);

    if (msg instanceof FullHttpRequest) {
        if (AppLoader.instances().get(0).runLevel() != RunLevel.RUNNING) {
            // Outputs a very crude raw message if we are running in a low level mode a.k.a. Startup or Reload.
            // While in the mode, much of the server API is potentially unavailable, that is why we do this.

            StringBuilder sb = new StringBuilder();
            sb.append("<h1>503 - Service Unavailable</h1>\n");
            sb.append(/*from ww w  .j av  a2  s  . com*/
                    "<p>I'm sorry to have to be the one to tell you this but the server is currently unavailable.</p>\n");
            sb.append(
                    "<p>This is most likely due to many possibilities, most commonly being it's currently booting up. Which would be great news because it means your request should succeed if you try again.</p>\n");
            sb.append(
                    "<p>But it is also possible that the server is actually running in a low level mode or could be offline for some other reason. If you feel this is a mistake, might I suggest you talk with the server admin.</p>\n");
            sb.append("<p><i>You have a good day now and we will see you again soon. :)</i></p>\n");
            sb.append("<hr>\n");
            sb.append("<small>Running <a href=\"https://github.com/ChioriGreene/ChioriWebServer\">"
                    + Versioning.getProduct() + "</a> Version " + Versioning.getVersion() + " (Build #"
                    + Versioning.getBuildNumber() + ")<br />" + Versioning.getCopyright() + "</small>");

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.valueOf(503), Unpooled.wrappedBuffer(sb.toString().getBytes()));
            ctx.write(response);

            return;
        }

        requestFinished = false;
        requestOrig = (FullHttpRequest) msg;
        request = new HttpRequestWrapper(ctx.channel(), requestOrig, this, ssl, log);
        response = request.getResponse();

        String threadName = Thread.currentThread().getName();

        if (threadName.length() > 10)
            threadName = threadName.substring(0, 2) + ".." + threadName.substring(threadName.length() - 6);
        else if (threadName.length() < 10)
            threadName = threadName + Strings.repeat(" ", 10 - threadName.length());

        log.header("&7[&d%s&7] %s %s [&9%s:%s&7] -> [&a%s:%s&7]", threadName,
                dateFormat.format(Timings.millis()), timeFormat.format(Timings.millis()), request.getIpAddr(),
                request.getRemotePort(), request.getLocalIpAddr(), request.getLocalPort());

        if (HttpHeaderUtil.is100ContinueExpected((HttpRequest) msg))
            send100Continue(ctx);

        if (NetworkSecurity.isIpBanned(request.getIpAddr())) {
            response.sendError(403);
            return;
        }

        Site currentSite = request.getLocation();

        File tmpFileDirectory = currentSite != null ? currentSite.directoryTemp()
                : AppConfig.get().getDirectoryCache();

        setTempDirectory(tmpFileDirectory);

        if (request.isWebsocketRequest()) {
            try {
                WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                        request.getWebSocketLocation(requestOrig), null, true);
                handshaker = wsFactory.newHandshaker(requestOrig);
                if (handshaker == null)
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                else
                    handshaker.handshake(ctx.channel(), requestOrig);
            } catch (WebSocketHandshakeException e) {
                NetworkManager.getLogger().severe(
                        "A request was made on the websocket uri '/fw/websocket' but it failed to handshake for reason '"
                                + e.getMessage() + "'.");
                response.sendError(500, null, "This URI is for websocket requests only<br />" + e.getMessage());
            }
            return;
        }

        if (request.method() != HttpMethod.GET)
            try {
                decoder = new HttpPostRequestDecoder(factory, requestOrig);
            } catch (ErrorDataDecoderException e) {
                e.printStackTrace();
                response.sendException(e);
                return;
            }

        request.contentSize += requestOrig.content().readableBytes();

        if (decoder != null) {
            try {
                decoder.offer(requestOrig);
            } catch (ErrorDataDecoderException e) {
                e.printStackTrace();
                response.sendError(e);
                // ctx.channel().close();
                return;
            } catch (IllegalArgumentException e) {
                // TODO Handle this further? maybe?
                // java.lang.IllegalArgumentException: empty name
            }
            readHttpDataChunkByChunk();
        }

        handleHttp();

        finish();
    } else if (msg instanceof WebSocketFrame) {
        WebSocketFrame frame = (WebSocketFrame) msg;

        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }

        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        if (!(frame instanceof TextWebSocketFrame))
            throw new UnsupportedOperationException(
                    String.format("%s frame types are not supported", frame.getClass().getName()));

        String request = ((TextWebSocketFrame) frame).text();
        NetworkManager.getLogger()
                .fine("Received '" + request + "' over WebSocket connection '" + ctx.channel() + "'");
        ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));
    } else if (msg instanceof DefaultHttpRequest) {
        // Do Nothing!
    } else
        NetworkManager.getLogger().warning(
                "Received Object '" + msg.getClass() + "' and had nothing to do with it, is this a bug?");
}

From source file:com.cmz.http.websocketx.benchmarkserver.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from  w  w w.j ava  2 s.  c  om
    }

    // Allow only GET methods.
    if (req.method() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.uri())) {
        ByteBuf content = WebSocketServerBenchmarkPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.uri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true, 5 * 1024 * 1024);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java

License:Apache License

private void handshake(ChannelHandlerContext ctx, final UUID sessionId, String path, FullHttpRequest req) {
    final Channel channel = ctx.channel();

    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, false, configuration.getMaxFramePayloadLength());
    WebSocketServerHandshaker handshaker = factory.newHandshaker(req);
    if (handshaker != null) {
        ChannelFuture f = handshaker.handshake(channel, req);
        f.addListener(new ChannelFutureListener() {
            @Override//ww  w  .java  2s. c  o  m
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.error("Can't handshake " + sessionId, future.cause());
                    return;
                }

                channel.pipeline().addBefore(SocketIOChannelInitializer.WEB_SOCKET_TRANSPORT,
                        SocketIOChannelInitializer.WEB_SOCKET_AGGREGATOR,
                        new WebSocketFrameAggregator(configuration.getMaxFramePayloadLength()));
                connectClient(channel, sessionId);
            }
        });
    } else {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    }
}

From source file:com.earasoft.framework.http.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    // Handle a bad request.
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;/*  ww w  .j a  v  a  2  s  .  c om*/
    }

    if (RouterHits.checkIfMappingExit(request)) {
        //Do Router Mapping First
        RouterHits.execute(ctx, request);
        return;
    }

    if ("/websocket".equals(request.getUri())) {
        // Handshake
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(request), null, true);
        handshaker = wsFactory.newHandshaker(request);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), request);
            channels.add(ctx.channel());
        }
        return;
    }

    final String uri = request.getUri();
    //System.out.println("uri: " + uri);
    final String path = sanitizeUri("www", uri);
    //System.out.println("path: " + path);
    if (path == null) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));

        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {

            File checkIndexFile = new File(file.getAbsolutePath() + File.separator + "index.html");

            System.out.println(checkIndexFile.exists());
            if (checkIndexFile.exists()) {
                file = checkIndexFile;
            } else {
                sendListing(ctx, file);
                return;
            }
        } else {
            sendRedirect(ctx, uri + '/');

        }
    }

    if (!file.isFile()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = null;
        try {
            ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
        return;
    }
    long fileLength = 0;
    try {
        fileLength = raf.length();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture = null;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        try {
            sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                    ctx.newProgressivePromise());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }

    //        // Send the demo page and favicon.ico
    //        if ("/".equals(req.getUri()) && req.getMethod() == GET) {
    //            ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    //
    //            res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    //            HttpHeaders.setContentLength(res, content.readableBytes());
    //
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }
    //        
    //        if ("/favicon.ico".equals(req.getUri())) {
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }

    sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));
    return;

}

From source file:com.fanavard.challenge.server.websocket.server.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//  w ww . ja va2  s  . c o m
    }

    // Allow only GET methods.
    if (req.method() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.uri())) {
        ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaderUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.uri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}