Example usage for io.netty.handler.codec.http.websocketx WebSocketFrame retain

List of usage examples for io.netty.handler.codec.http.websocketx WebSocketFrame retain

Introduction

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

Prototype

@Override
    public WebSocketFrame retain() 

Source Link

Usage

From source file:app.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        channels.remove(ctx.channel());//from   www .j  a va  2  s  . c  om
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (frame instanceof TextWebSocketFrame) {
        JSONObject msg = (JSONObject) JSONValue.parse(((TextWebSocketFrame) frame).text());

        if (msg == null) {
            System.out.println("Unknown message type");
            return;
        }

        switch (msg.get("type").toString()) {
        case "broadcast":
            final TextWebSocketFrame outbound = new TextWebSocketFrame(msg.toJSONString());
            channels.forEach(gc -> gc.writeAndFlush(outbound.duplicate().retain()));
            msg.replace("type", "broadcastResult");
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        case "echo":
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        default:
            System.out.println("Unknown message type");
        }

        return;
    }
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // ?//from   w  ww  .ja  v a2s . c om
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    // ?Ping?
    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 not supported", frame.getClass().getName()));
    }

    // ?
    String request = ((TextWebSocketFrame) frame).text();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format("%s received %s", ctx.channel(), request));
    }
    ctx.channel().write(new TextWebSocketFrame(request
            + " , Netty WebSocket?" + new java.util.Date().toString()));
}

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

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/*w w  w .  java  2  s  .  com*/
    }
    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 not supported", frame.getClass().getName()));
    }

    // Send the uppercase string back.
    String request = ((TextWebSocketFrame) frame).text();
    System.err.printf("%s received %s%n", ctx.channel(), request);
    ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));
}

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

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/* ww w.ja v a 2  s. c o m*/
    }
    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 not supported", frame.getClass().getName()));
    }

    //??{cmd:getSensorValue,depth:0,timeInterval:1000,sensorIds:[...]},?????
    String request = ((TextWebSocketFrame) frame).text();
    JSONObject reqObj = JSON.parseObject(request);
    if (reqObj.containsKey("cmd")) {
        String cmd = reqObj.getString("cmd");
        switch (cmd) {
        case "getStartTime":
            getStartTime(ctx);
            break;
        case "getSensorCount":
            getSensorCount(ctx);
            break;
        case "getSensorValue"://?
            getSensorValue(reqObj, ctx);
            break;
        case "updateSensorValue"://?
            updateSensorValue(reqObj, ctx);
            break;
        case "getCachePoolDepth":
            getCachePoolDepth(reqObj, ctx);
            break;
        case "getSensorHandlers":
            getSensorHandlers(reqObj, ctx);
            break;
        default:
            ctx.writeAndFlush(new TextWebSocketFrame(""));
            break;
        }
    } else {
        log.warn("unknown command");
        ctx.writeAndFlush(new TextWebSocketFrame("?"));
    }

    //ctx.executor().scheduleAtFixedRate(paramRunnable, paramLong1, paramLong2, paramTimeUnit)

}

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

License:Open Source License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/*  ww  w . ja  v a 2 s .  c om*/
    }

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

    if (frame instanceof ContinuationWebSocketFrame)
        return;

    if (frame instanceof TextWebSocketFrame)
        webSocketActor.onMessage(((TextWebSocketFrame) frame).text());
    else
        webSocketActor.onMessage(frame.content().nioBuffer());
}

From source file:com.adobe.acs.livereload.impl.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/* w  w  w  .java 2  s  .  co  m*/
    }
    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 not supported", frame.getClass().getName()));
    }

    String request = ((TextWebSocketFrame) frame).text();
    try {
        JSONObject obj = new JSONObject(request);
        handleCommand(obj, ctx);

    } catch (JSONException e) {
        throw new IllegalArgumentException(String.format("%s is not a valid JSON object", request));
    }

}

From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        try {/*  w w w  . j  a  v  a 2  s.c  o  m*/
            fos.flush();
            fos.close();
            fos = null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }

    if (frame instanceof TextWebSocketFrame) {

        // Send the uppercase string back.
        String fileName = ((TextWebSocketFrame) frame).text();
        logger.debug(String.format("Received file name is [%s]", fileName));

        destFile = new File(fileName + ".received");
        try {
            fos = new FileOutputStream(destFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ctx.channel().write(new TextWebSocketFrame(fileName.toUpperCase()));
    }

    if (frame instanceof BinaryWebSocketFrame) {
        byte[] buffer = null;
        ByteBuf rawMessage = ((BinaryWebSocketFrame) frame).content();

        //logger.debug(">>>> BinaryWebSocketFrame Found, " + rawMessage);
        // check if this ByteBuf is DIRECT (no backing byte[])
        if (rawMessage.hasArray() == false) {
            int size = rawMessage.readableBytes();
            buffer = new byte[size];
            rawMessage.readBytes(buffer);

            try {
                fos.write(buffer);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            buffer = rawMessage.array();
        }
        logger.debug(">>>> Read Byte Array: " + buffer.length);

        return;
    }
}

From source file:com.athena.dolly.websocket.server.test.WebSocketSslServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/*from  w  ww  .j  a  v  a 2  s  . c  o m*/
    }
    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 not supported", frame.getClass().getName()));
    }

    // Send the uppercase string back.
    String request = ((TextWebSocketFrame) frame).text();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format("%s received %s", ctx.channel(), request));
    }
    ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));
}

From source file:com.brainlounge.zooterrain.netty.WebSocketServerInboundHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/* w w  w.j  ava  2  s.  c  o  m*/
    }
    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 not supported", frame.getClass().getName()));
    }

    String request = ((TextWebSocketFrame) frame).text();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format("%s received %s", ctx.channel(), request));
    }

    // expecting JSON, parse now
    TreeNode jsonRequest;
    ClientRequest.Type requestType;
    try {
        final JsonParser parser = jsonMapper.getFactory().createParser(request);
        jsonRequest = parser.readValueAsTree();
        TextNode type = (TextNode) jsonRequest.get("r");
        requestType = ClientRequest.Type.valueOf(type.textValue());
    } catch (Exception e) {
        logger.info("parsing JSON failed for '" + request + "'");
        // TODO return error to client
        return;
    }

    if (requestType == ClientRequest.Type.i) {
        // client requested initial data

        // sending connection string info
        final ControlMessage handshakeInfo = new ControlMessage(zkStateObserver.getZkConnection(),
                ControlMessage.Type.H);
        writeClientMessage(ctx, handshakeInfo);

        // sending initial znodes
        try {
            zkStateObserver.initialTree("/", 6, Sets.<ZkStateListener>newHashSet(new OutboundConnector(ctx)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } else if (requestType == ClientRequest.Type.b) {
        final String znode;
        try {
            znode = ((TextNode) jsonRequest.get("z")).textValue();
        } catch (Exception e) {
            return; // TODO return error
        }
        final DataMessage dataMessage = zkStateObserver.retrieveNodeData(znode);
        if (dataMessage != null) {
            writeClientMessage(ctx, dataMessage);
        }
    } else {
        System.out.println("unknown, unhandled client request = " + request);
    }
}

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(/*  w  w  w  .  j a v a  2  s  .  c o m*/
                    "<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?");
}