Java 类io.netty.handler.codec.http.websocketx.PingWebSocketFrame 实例源码

项目:java_learn    文件:WebSocketServerHandler.java   
private void handlerWebSocketFrame(ChannelHandlerContext ctx,
        WebSocketFrame frame) {
    // 判断是否关闭链路的指令
    if (frame instanceof CloseWebSocketFrame) {
        socketServerHandshaker.close(ctx.channel(),
                (CloseWebSocketFrame) frame.retain());
    }
    // 判断是否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();
    System.out.println("服务端收到:" + request);
    TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString()
            + ctx.channel().id() + ":" + request);
    // 群发
    group.writeAndFlush(tws);
}
项目:timely    文件:Subscription.java   
public Subscription(String subscriptionId, String sessionId, DataStore store, ChannelHandlerContext ctx,
        Configuration conf) {
    this.subscriptionId = subscriptionId;
    this.sessionId = sessionId;
    this.store = store;
    this.ctx = ctx;
    this.lag = conf.getWebsocket().getSubscriptionLag();
    this.scannerBatchSize = conf.getWebsocket().getScannerBatchSize();
    this.flushIntervalSeconds = conf.getWebsocket().getFlushIntervalSeconds();
    this.scannerReadAhead = conf.getWebsocket().getScannerReadAhead();
    this.subscriptionBatchSize = conf.getWebsocket().getSubscriptionBatchSize();
    // send a websocket ping at half the timeout interval.
    int rate = conf.getWebsocket().getTimeout() / 2;
    this.ping = this.ctx.executor().scheduleAtFixedRate(() -> {
        LOG.trace("Sending ping on channel {}", ctx.channel());
        ctx.writeAndFlush(new PingWebSocketFrame());
        cleanupCompletedMetrics();
    }, rate, rate, TimeUnit.SECONDS);
}
项目:megaphone    文件:WebSocketHandler.java   
private void handleFrame(Channel channel, WebSocketFrame frame, WebSocketUpgradeHandler handler, NettyWebSocket webSocket) throws Exception {
    if (frame instanceof CloseWebSocketFrame) {
        Channels.setDiscard(channel);
        CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) frame;
        webSocket.onClose(closeFrame.statusCode(), closeFrame.reasonText());
    } else {
        ByteBuf buf = frame.content();
        if (buf != null && buf.readableBytes() > 0) {
            HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(buf, frame.isFinalFragment());
            handler.onBodyPartReceived(part);

            if (frame instanceof BinaryWebSocketFrame) {
                webSocket.onBinaryFragment(part);
            } else if (frame instanceof TextWebSocketFrame) {
                webSocket.onTextFragment(part);
            } else if (frame instanceof PingWebSocketFrame) {
                webSocket.onPing(part);
            } else if (frame instanceof PongWebSocketFrame) {
                webSocket.onPong(part);
            }
        }
    }
}
项目:reactor-netty    文件:HttpServerWSOperations.java   
@Override
public void onInboundNext(ChannelHandlerContext ctx, Object frame) {
    if (frame instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) frame).isFinalFragment()) {
        if (log.isDebugEnabled()) {
            log.debug("CloseWebSocketFrame detected. Closing Websocket");
        }
        CloseWebSocketFrame close = (CloseWebSocketFrame) frame;
        sendClose(new CloseWebSocketFrame(true,
                close.rsv(),
                close.content()), f -> onHandlerTerminate());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) frame).content()));
        ctx.read();
        return;
    }
    super.onInboundNext(ctx, frame);
}
项目:zbus    文件:MessageCodec.java   
private Message decodeWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return null;
    }

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

    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        return parseMessage(textFrame.content());
    }

    if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame;
        return parseMessage(binFrame.content());
    }

    log.warn("Message format error: " + frame); 
    return null;
}
项目:JavaAyo    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }
        if (frame instanceof BinaryWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }
    }
项目:spring-cloud-stream-app-starters    文件:WebsocketSinkServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        addTraceForFrame(frame, "close");
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        addTraceForFrame(frame, "ping");
        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()));
    }

    // todo [om] think about BinaryWebsocketFrame

    handleTextWebSocketFrameInternal((TextWebSocketFrame) frame, ctx);
}
项目:snotel    文件:NettyFirehoseOnSubscribe.java   
@Override
protected void channelRead0(ChannelHandlerContext context, Object message) throws Exception {
    final Channel channel = context.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(channel, (FullHttpResponse) message);
        channel.pipeline().addBefore(HANDLER_NAME, "websocket-frame-aggregator", new WebSocketFrameAggregator(64 * 1024));
        subscriber.onStart();
        return;
    }

    if (message instanceof FullHttpResponse) {
        final FullHttpResponse response = (FullHttpResponse) message;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.getStatus() +
                        ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    final WebSocketFrame frame = (WebSocketFrame) message;
    if (frame instanceof PingWebSocketFrame) {
        context.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame)frame).retain().content()));
    } else if (frame instanceof BinaryWebSocketFrame) {
        final ByteBufInputStream input = new ByteBufInputStream(((BinaryWebSocketFrame)message).content());
        final Envelope envelope = Envelope.ADAPTER.decode(input);
        subscriber.onNext(envelope);
    }
}
项目:netty4.0.27Learn    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 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 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()));
    }
项目:netty4.0.27Learn    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }
        if (frame instanceof BinaryWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }
    }
项目:netty4.0.27Learn    文件:AutobahnServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format(
                "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame)));
    }

    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()), ctx.voidPromise());
    } else if (frame instanceof TextWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof ContinuationWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof PongWebSocketFrame) {
        frame.release();
        // Ignore
    } else {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                .getName()));
    }
}
项目:lambdatra    文件:WsAdapter.java   
@Override
public void accept(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        endpoint.releaseReferences();
        endpoint.onClose();
        return;
    }

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

    if (frame instanceof TextWebSocketFrame) {
        endpoint.onMessage(((TextWebSocketFrame) frame).text());
        return;
    }

    throw new UnsupportedOperationException(String.format("Unsupported websocket frame of type %s", frame.getClass().getName()));
}
项目:brent-pusher    文件:NettyPusherServer.java   
private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    // 判断是否关闭链路的指令
    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)) {
        ctx.close();//(String.format("%s frame types not supported", frame.getClass().getName()));
        return;
    }

}
项目:netty-rest    文件:WebSocketService.java   
public void handle(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
        onClose(ctx);
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content()));
        return;
    }
    if (!(frame instanceof TextWebSocketFrame)) {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                .getName()));
    }

    String msg = ((TextWebSocketFrame) frame).text();
    onMessage(ctx, msg);
}
项目:netty-study    文件:WebSocketServerHandler.java   
public void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 判断是否是关闭链路的指令
        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();
        System.out.println(String.format("%s received %s", ctx.channel(), request));

        ctx.channel().write(new TextWebSocketFrame(request+" ,现在时刻:"+new Date()));

    }
项目:carbon-transports    文件:WebSocketSourceHandler.java   
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws UnknownWebSocketFrameTypeException, ServerConnectorException {
    if (!(msg instanceof WebSocketFrame)) {
        logger.error("Expecting WebSocketFrame. Unknown type.");
        throw new UnknownWebSocketFrameTypeException("Expecting WebSocketFrame. Unknown type.");
    }
    if (msg instanceof TextWebSocketFrame) {
        notifyTextMessage((TextWebSocketFrame) msg);
    } else if (msg instanceof BinaryWebSocketFrame) {
        notifyBinaryMessage((BinaryWebSocketFrame) msg);
    } else if (msg instanceof CloseWebSocketFrame) {
        notifyCloseMessage((CloseWebSocketFrame) msg);
    } else if (msg instanceof PingWebSocketFrame) {
        notifyPingMessage((PingWebSocketFrame) msg);
    } else if (msg instanceof PongWebSocketFrame) {
        notifyPongMessage((PongWebSocketFrame) msg);
    }
}
项目:carbon-transports    文件:WebSocketRemoteServerFrameHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    if (frame instanceof TextWebSocketFrame) {
        // Echos the same text
        String text = ((TextWebSocketFrame) frame).text();
        if (PING.equals(text)) {
            ctx.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[]{1, 2, 3, 4})));
            return;
        }
        ctx.channel().writeAndFlush(new TextWebSocketFrame(text));
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.channel().writeAndFlush(frame.retain());
    } else if (frame instanceof CloseWebSocketFrame) {
        ctx.close();
    } else {
        String message = "unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }
}
项目:netty4study    文件:AutobahnServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format(
                "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame)));
    }

    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()), ctx.voidPromise());
    } else if (frame instanceof TextWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof ContinuationWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof PongWebSocketFrame) {
        frame.release();
        // Ignore
    } else {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                .getName()));
    }
}
项目:netty4study    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 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 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()));
    }
项目:netty4study    文件:WebSocketSslServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 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 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()));
    }
项目:modules-extra    文件:WebSocketRequestHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception
{
    this.last = ctx;
    if (frame instanceof CloseWebSocketFrame)
    {
        this.log.debug("recevied close frame");
        this.server.unsubscribe(this);
        this.handshaker.close(ctx.channel(), (CloseWebSocketFrame)frame);
    }
    else if (frame instanceof PingWebSocketFrame)
    {
        this.log.debug("recevied ping frame");
        ctx.write(new PongWebSocketFrame(frame.content()));
    }
    else if (frame instanceof TextWebSocketFrame)
    {
        this.log.debug("recevied text frame");
        this.handleTextWebSocketFrame(ctx, (TextWebSocketFrame)frame);
    }
    else
    {
        this.log.info("recevied unknown incompatible frame");
        ctx.close();
    }
}
项目:Surf    文件:HttpServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    _logger.debug("Handling websocket frame");
    // 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 not supported", frame.getClass()
                .getName()));
    }

    String request = ((TextWebSocketFrame) frame).text();
    _logger.debug("{} received {}", ctx.channel(), request);
    _messageQueue.add(frame.content().retain());
    //ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 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 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()));
    }
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketSslServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 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 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()));
    }
项目:netty-netty-5.0.0.Alpha1    文件:AutobahnServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format(
                "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame)));
    }

    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()));
    } else if (frame instanceof TextWebSocketFrame) {
        ctx.write(frame);
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.write(frame);
    } else if (frame instanceof ContinuationWebSocketFrame) {
        ctx.write(frame);
    } else if (frame instanceof PongWebSocketFrame) {
        frame.release();
        // Ignore
    } else {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                .getName()));
    }
}
项目:laputa    文件:LaputaServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
  // Check for closing frame
  if (frame instanceof CloseWebSocketFrame) {
    handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
    return;
  }
  if (frame instanceof PingWebSocketFrame) {
    ctx.write(new PongWebSocketFrame(frame.content().retain()));
    return;
  }
  if (frame instanceof TextWebSocketFrame) {
    // Echo the frame
    ctx.write(frame.retain());
    return;
  }
  if (frame instanceof BinaryWebSocketFrame) {
    // Echo the frame
    ctx.write(frame.retain());
  }
}
项目:top-traffic    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame 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 BinaryWebSocketFrame)
        try {
            this.connection.onMessage(((BinaryWebSocketFrame) frame).content().retain());
        } catch (Exception e) {
            logger.error("onMessage error", e);
            handshaker.close(ctx.channel(),
                    new CloseWebSocketFrame(true, 0,
                            frame.content().clear()
                                    .writeShort(1000)
                                    .writeBytes(e.getMessage().getBytes(CharsetUtil.UTF_8))
                                    .retain()));
        }
}
项目:socketio    文件:WebSocketHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
  if (log.isDebugEnabled())
    log.debug("Received {} WebSocketFrame: {} from channel: {}", getTransportType().getName(), msg, ctx.channel());

  if (msg instanceof CloseWebSocketFrame) {
    sessionIdByChannel.remove(ctx.channel());
    ChannelFuture f = ctx.writeAndFlush(msg);
    f.addListener(ChannelFutureListener.CLOSE);
  } else if (msg instanceof PingWebSocketFrame) {
    ctx.writeAndFlush(new PongWebSocketFrame(msg.content()));
  } else if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame){
    Packet packet = PacketDecoder.decodePacket(msg.content());
    packet.setTransportType(getTransportType());
    String sessionId = sessionIdByChannel.get(ctx.channel());
    packet.setSessionId(sessionId);
    msg.release();
    ctx.fireChannelRead(packet);
  } else {
    msg.release();
    log.warn("{} frame type is not supported", msg.getClass().getName());
  }
}
项目:qonduit    文件:WebSocketIT.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    LOG.info("Received msg: {}", msg);
    if (!this.handshaker.isHandshakeComplete()) {
        this.handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
        LOG.info("Client connected.");
        this.connected = true;
        this.handshakeFuture.setSuccess();
        return;
    }
    if (msg instanceof FullHttpResponse) {
        throw new IllegalStateException("Unexpected response: " + msg.toString());
    }
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        synchronized (responses) {
            responses.add(((TextWebSocketFrame) frame).text().getBytes(StandardCharsets.UTF_8));
        }
    } else if (frame instanceof BinaryWebSocketFrame) {
        ByteBuf buf = frame.content();
        byte[] b = new byte[buf.readableBytes()];
        buf.readBytes(b);
        synchronized (responses) {
            responses.add(b);
        }
    } else if (frame instanceof PingWebSocketFrame) {
        LOG.info("Returning pong message");
        ctx.writeAndFlush(new PongWebSocketFrame());
    } else if (frame instanceof CloseWebSocketFrame) {
        LOG.info("Received message from server to close the channel.");
        ctx.close();
    } else {
        LOG.warn("Unhandled frame type received: " + frame.getClass());
    }
}
项目:timely    文件:WebSocketIT.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    LOG.info("Received msg: {}", msg);
    if (!this.handshaker.isHandshakeComplete()) {
        this.handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
        LOG.info("Client connected.");
        this.connected = true;
        this.handshakeFuture.setSuccess();
        return;
    }
    if (msg instanceof FullHttpResponse) {
        throw new IllegalStateException("Unexpected response: " + msg.toString());
    }
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        synchronized (responses) {
            responses.add(((TextWebSocketFrame) frame).text());
        }
    } else if (frame instanceof PingWebSocketFrame) {
        LOG.info("Returning pong message");
        ctx.writeAndFlush(new PongWebSocketFrame());
    } else if (frame instanceof CloseWebSocketFrame) {
        LOG.info("Received message from server to close the channel.");
        ctx.close();
    } else {
        LOG.warn("Unhandled frame type received: " + frame.getClass());
    }
}
项目:product-ei    文件:WebSocketTestClient.java   
/**
 * Send a ping message to the server.
 *
 * @param buf content of the ping message to be sent.
 */
public void sendPing(ByteBuffer buf) throws IOException {
    if (channel == null) {
        logger.error("Channel is null. Cannot send text.");
        throw new IllegalArgumentException("Cannot find the channel to write");
    }
    channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf)));
}
项目:khs-stockticker    文件:StockTickerServerHandler.java   
protected void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
   logger.debug("Received incoming frame [{}]", frame.getClass().getName());
   // Check for closing frame
   if (frame instanceof CloseWebSocketFrame) {
      if (frameBuffer != null) {
          handleMessageCompleted(ctx, frameBuffer.toString());
      }
      handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
      return;
   }

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

   if (frame instanceof PongWebSocketFrame) {
      logger.info("Pong frame received");
      return;
   }

   if (frame instanceof TextWebSocketFrame) {
      frameBuffer = new StringBuilder();
      frameBuffer.append(((TextWebSocketFrame)frame).text());
   } else if (frame instanceof ContinuationWebSocketFrame) {
      if (frameBuffer != null) {
         frameBuffer.append(((ContinuationWebSocketFrame)frame).text());
      } else {
         logger.warn("Continuation frame received without initial frame.");
      }
   } else {
      throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
   }

   // Check if Text or Continuation Frame is final fragment and handle if needed.
   if (frame.isFinalFragment()) {
      handleMessageCompleted(ctx, frameBuffer.toString());
      frameBuffer = null;
   }
}
项目:netty-book    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx,
    WebSocketFrame frame) {

// 判断是否是关闭链路的指令
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()));
   }
项目:msf4j    文件:WebSocketClient.java   
/**
 * Send a ping message to the server.
 * @param buf content of the ping message to be sent.
 */
public void sendPing(ByteBuffer buf) throws IOException {
    if (channel == null) {
        logger.error("Channel is null. Cannot send text.");
        throw new IllegalArgumentException("Cannot find the channel to write");
    }
    channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf)));
}
项目:carbon-transports    文件:WebSocketSourceHandler.java   
private void notifyPingMessage(PingWebSocketFrame pingWebSocketFrame) throws ServerConnectorException {
    //Control message for WebSocket is Ping Message
    ByteBuf byteBuf = pingWebSocketFrame.content();
    ByteBuffer byteBuffer = byteBuf.nioBuffer();
    WebSocketMessageImpl webSocketControlMessage =
            new WebSocketControlMessageImpl(WebSocketControlSignal.PING, byteBuffer);
    webSocketControlMessage = setupCommonProperties(webSocketControlMessage);
    connectorFuture.notifyWSListener((WebSocketControlMessage) webSocketControlMessage);
}
项目:carbon-transports    文件:WebSocketTargetHandler.java   
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg)
        throws UnknownWebSocketFrameTypeException, URISyntaxException, ServerConnectorException {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.debug("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        channelSession = WebSocketUtil.getSession(ctx, isSecure, requestedUri);
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.status() +
                        ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        notifyTextMessage((TextWebSocketFrame) frame, ctx);
    } else if (frame instanceof BinaryWebSocketFrame) {
        notifyBinaryMessage((BinaryWebSocketFrame) frame, ctx);
    } else if (frame instanceof PongWebSocketFrame) {
        notifyPongMessage((PongWebSocketFrame) frame, ctx);
    } else if (frame instanceof PingWebSocketFrame) {
        notifyPingMessage((PingWebSocketFrame) frame, ctx);
    } else if (frame instanceof CloseWebSocketFrame) {
        if (channelSession != null) {
            channelSession.setIsOpen(false);
        }
        notifyCloseMessage((CloseWebSocketFrame) frame, ctx);
        ch.close();
    } else {
        throw new UnknownWebSocketFrameTypeException("Cannot identify the WebSocket frame type");
    }
}
项目:carbon-transports    文件:WebSocketTargetHandler.java   
private void notifyPingMessage(PingWebSocketFrame pingWebSocketFrame, ChannelHandlerContext ctx)
        throws ServerConnectorException {
    //Control message for WebSocket is Ping Message
    ByteBuf byteBuf = pingWebSocketFrame.content();
    ByteBuffer byteBuffer = byteBuf.nioBuffer();
    WebSocketMessageImpl webSocketControlMessage =
            new WebSocketControlMessageImpl(WebSocketControlSignal.PING, byteBuffer);
    webSocketControlMessage = setupCommonProperties(webSocketControlMessage, ctx);
    connectorListener.onMessage((WebSocketControlMessage) webSocketControlMessage);
}
项目:carbon-transports    文件:WebSocketTestClient.java   
/**
 * Send a ping message to the server.
 * @param buf content of the ping message to be sent.
 */
public void sendPing(ByteBuffer buf) throws IOException {
    if (channel == null) {
        logger.error("Channel is null. Cannot send text.");
        throw new IllegalArgumentException("Cannot find the channel to write");
    }
    channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf)));
}
项目:activemq-artemis    文件:WebSocketServerHandler.java   
private boolean handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

      // Check for closing frame
      if (frame instanceof CloseWebSocketFrame) {
         this.handshaker.close(ctx.channel(), ((CloseWebSocketFrame) frame).retain());
         return false;
      } else if (frame instanceof PingWebSocketFrame) {
         ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
         return false;
      } else if (!(frame instanceof TextWebSocketFrame) && !(frame instanceof BinaryWebSocketFrame)) {
         throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
      }
      return true;
   }
项目:NettyStages    文件:WebSocketServerHandler.java   
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 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 not supported", frame.getClass()
                    .getName()));
        }

        // Send the uppercase string back.
        TextWebSocketFrame frame2 = (TextWebSocketFrame) frame;

        String request = frame2.text();


        Thread t = Thread.currentThread();
        System.err.printf("%s received %s%n thread %d ", ctx.channel(), request, t.getId());        



        ///////////////////
        //Do your work here
        ///////////////////


        ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));

    }