com.youtubeshare.netty.handler.WebSocketHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.youtubeshare.netty.handler.WebSocketHandler.java

Source

/*
 * Copyright 2014 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.youtubeshare.netty.handler;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.youtubeshare.bean.ApplicationContextProvider;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * WebSocketHandler.java
 * @author 
 * @date 2016. 3. 22.
 *  ? ?
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger LOGGER = Logger.getLogger(WebSocketHandler.class);

    @Autowired
    private ApplicationContextProvider acp;
    @Autowired
    private FullHttpRequestHandler fullHttpRequestHandler;
    @Autowired
    private TextWebSocketFrameHandler textWebSocketFrameHandler;
    private WebSocketServerHandshaker handshaker = null;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof TextWebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        } else if (msg instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), ((CloseWebSocketFrame) msg).retain());
            return;
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {

        String reqUri = getUri(req);

        // Handshake
        handshaker = acp.getContext().getBean(WebSocketServerHandshaker.class, reqUri, req);

        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            ChannelFuture f = handshaker.handshake(ctx.channel(), req);
            //handshake ? ?  ?
            f.addListener(future -> fullHttpRequestHandler.handling(ctx, req));
        }
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof TextWebSocketFrame) {
            textWebSocketFrameHandler.handling(ctx, (TextWebSocketFrame) frame);
            return;
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        fullHttpRequestHandler.inActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof IOException == false) { //??   ?  ?   
            cause.printStackTrace();
            LOGGER.error("[WebSocketHandler] -> execeptionCaught : " + cause.getMessage());
        }
        fullHttpRequestHandler.inActive(ctx);
        ctx.close();
    }

    private String getUri(FullHttpRequest req) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("wss://");
        stringBuilder.append(req.headers().get(HttpHeaderNames.HOST));
        stringBuilder.append("/");
        stringBuilder.append(req.uri());
        return stringBuilder.toString();
    }
}