Java Code Examples for io.netty.handler.codec.http.FullHttpResponse#status()

The following examples show how to use io.netty.handler.codec.http.FullHttpResponse#status() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultPampasResponse.java    From pampas with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    String body = null;
    Object status = null;
    if (responseData != null && responseData instanceof FullHttpResponse) {
        FullHttpResponse httpResponse = (FullHttpResponse) this.responseData;
        ByteBuf content = httpResponse.content();
        body = content.toString(UTF_8);
        status = httpResponse.status();
    }

    return MoreObjects.toStringHelper(this)
            .omitNullValues()
            .add("id", id)
            .add("success", success)
            .add("status", status)
            .add("responseData", body == null ? responseData : body)
            .add("exception", exception)
            .toString();
}
 
Example 2
Source File: NettyHttpClientHandler.java    From ari4java with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        responseBytes = new byte[response.content().readableBytes()];
        response.content().readBytes(responseBytes);
        responseStatus = response.status();
        HTTPLogger.traceResponse(response, responseBytes);
        if (response.headers().get(HttpHeaderNames.CONTENT_LENGTH) != null) {
            if (responseBytes.length != response.headers().getInt(HttpHeaderNames.CONTENT_LENGTH)) {
                logger.error("HTTP Content-Length: {}, but body read: {}",
                        response.headers().getInt(HttpHeaderNames.CONTENT_LENGTH), responseBytes.length);
            }
        }
    } else if (msg != null) {
        logger.warn("Unexpected: {}", msg.toString());
        throw new RestException("Unknown object: " + msg.getClass().getSimpleName() + ", expecting FullHttpResponse");
    }
}
 
Example 3
Source File: WebSocketClientHandshaker08.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 4
Source File: WebSocketClientHandshaker13.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 5
Source File: WebSocketClientHandler.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
private void handleHttpResponse(ChannelHandlerContext ctx, FullHttpResponse response) {
	if (!this.handshaker.isHandshakeComplete()) {
		try {
			this.handshaker.finishHandshake(ctx.channel(), response);
			///设置成功
			//this.handshakeFuture.setSuccess();
			System.out.println("WebSocket Client connected! response headers[sec-websocket-extensions]:{}"
					+ response.headers());
		} catch (WebSocketHandshakeException var7) {
			String errorMsg = String.format("WebSocket Client failed to connect,status:%s,reason:%s",
					response.status(), response.content().toString(CharsetUtil.UTF_8));
			NettyLog.error(errorMsg, var7);
			///this.handshakeFuture.setFailure(new Exception(errorMsg));
		}
	} else {
		throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
				+ ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
	}
}
 
Example 6
Source File: WebsocketConnectionBuilder.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            handshakeFuture.complete(connectFunction.apply(ch));
            ch.pipeline().remove(this);

        } catch (Exception e) {
            handshakeFuture.completeExceptionally(e);
        }
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.status() +
                        ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }
}
 
Example 7
Source File: WebSocketClientHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            System.out.println("WebSocket Client connected!");
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            System.out.println("WebSocket Client failed to connect");
            handshakeFuture.setFailure(e);
        }
        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) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        System.out.println("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 8
Source File: WebSocketClientHandler.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.status() +
                        ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        log.trace("WebSocket Client received message: " + binaryFrame.content());
        ctx.fireChannelRead(binaryFrame.retain().content());
    } else if (frame instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 9
Source File: TestUtils.java    From serve with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
    httpStatus = msg.status();
    result = msg.content().toString(StandardCharsets.UTF_8);
    headers = msg.headers();
    latch.countDown();
}
 
Example 10
Source File: AppWebSocketClientHandler.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.status() +
                        ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
    }

    if (msg instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
        log.trace("WebSocket Client received message: " + frame.content());
        ctx.fireChannelRead(((WebSocketFrame) msg).retain());
    } else if (msg instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 11
Source File: WebSocketClientHandler.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    final Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        // web socket client connected
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        handshakeFuture.setSuccess();
        return;
    }

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

    final WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        final TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        clientJSONPoint.onMessage(textFrame.text());
        if (LogHelper.isDevEnabled()) {
            LogHelper.dev("Message: %s", textFrame.text());
        }
        // uncomment to print request
        // logger.info(textFrame.text());
    } else if ((frame instanceof PingWebSocketFrame)) {
        frame.content().retain();
        ch.writeAndFlush(new PongWebSocketFrame(frame.content()), ch.voidPromise());
        //return;
    } else if (frame instanceof PongWebSocketFrame) {
    } else if (frame instanceof CloseWebSocketFrame)
        ch.close();
    else if (frame instanceof BinaryWebSocketFrame) {
        // uncomment to print request
        // logger.info(frame.content().toString());
    }

}
 
Example 12
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
    httpStatus = msg.status();
    result = msg.content().toString(StandardCharsets.UTF_8);
    headers = msg.headers();
    latch.countDown();
}
 
Example 13
Source File: WebSocketClientHandler.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            System.out.println("WebSocket Client connected!");
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            System.out.println("WebSocket Client failed to connect");
            handshakeFuture.setFailure(e);
        }
        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) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        System.out.println("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 14
Source File: WebSocketClientHandler.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    final Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        // web socket client connected
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        handshakeFuture.setSuccess();
        return;
    }

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

    // a close frame doesn't mean much here.  errors raised from closed channels will mark the host as dead
    final WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        ctx.fireChannelRead(frame.retain(2));
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.writeAndFlush(new PongWebSocketFrame());
    }else if (frame instanceof PongWebSocketFrame) {
        logger.debug("Received response from keep-alive request");
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.fireChannelRead(frame.retain(2));
    } else if (frame instanceof CloseWebSocketFrame)
        ch.close();

}
 
Example 15
Source File: BitsoWebSocket.java    From bitso-java with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {
    Channel channel = ctx.channel();

    if(!mHandshaker.isHandshakeComplete()) {
        mHandshaker.finishHandshake(channel, (FullHttpResponse) msg);
        mHandshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        setMessageReceived(textFrame.text());
    }
    
    if(frame instanceof CloseWebSocketFrame){
        setConnected(Boolean.FALSE);
    }
}
 
Example 16
Source File: NettyWSTransport.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object message) throws Exception {
   LOG.trace("New data read: incoming: {}", message);

   Channel ch = ctx.channel();
   if (!handshaker.isHandshakeComplete()) {
      handshaker.finishHandshake(ch, (FullHttpResponse) message);
      LOG.trace("WebSocket Client connected! {}", ctx.channel());
      // Now trigger super processing as we are really connected.
      NettyWSTransport.super.handleConnected(ch);
      return;
   }

   // We shouldn't get this since we handle the handshake previously.
   if (message instanceof FullHttpResponse) {
      FullHttpResponse response = (FullHttpResponse) message;
      throw new IllegalStateException(
         "Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
   }

   WebSocketFrame frame = (WebSocketFrame) message;
   if (frame instanceof TextWebSocketFrame) {
      TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
      LOG.warn("WebSocket Client received message: " + textFrame.text());
      ctx.fireExceptionCaught(new IOException("Received invalid frame over WebSocket."));
   } else if (frame instanceof BinaryWebSocketFrame) {
      BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
      LOG.trace("WebSocket Client received data: {} bytes", binaryFrame.content().readableBytes());
      listener.onData(binaryFrame.content());
   } else if (frame instanceof ContinuationWebSocketFrame) {
      ContinuationWebSocketFrame continuationFrame = (ContinuationWebSocketFrame) frame;
      LOG.trace("WebSocket Client received data continuation: {} bytes", continuationFrame.content().readableBytes());
      listener.onData(continuationFrame.content());
   } else if (frame instanceof PingWebSocketFrame) {
      LOG.trace("WebSocket Client received ping, response with pong");
      ch.write(new PongWebSocketFrame(frame.content()));
   } else if (frame instanceof CloseWebSocketFrame) {
      LOG.trace("WebSocket Client received closing");
      ch.close();
   }
}
 
Example 17
Source File: NettyWsTransport.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object message) throws Exception {
    LOG.trace("New data read: incoming: {}", message);

    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) message);
        LOG.trace("WebSocket Client connected! {}", ctx.channel());
        // Now trigger super processing as we are really connected.
        if(handshakeTimeoutFuture.cancel(false)) {
            NettyWsTransport.super.handleConnected(ch);
        }
        return;
    }

    // We shouldn't get this since we handle the handshake previously.
    if (message instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) message;
        throw new IllegalStateException(
            "Unexpected FullHttpResponse (getStatus=" + response.status() +
            ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) message;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        LOG.warn("WebSocket Client received message: " + textFrame.text());
        ctx.fireExceptionCaught(new IOException("Received invalid frame over WebSocket."));
    } else if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        LOG.trace("WebSocket Client received data: {} bytes", binaryFrame.content().readableBytes());
        listener.onData(binaryFrame.content());
    } else if (frame instanceof ContinuationWebSocketFrame) {
        ContinuationWebSocketFrame continuationFrame = (ContinuationWebSocketFrame) frame;
        LOG.trace("WebSocket Client received data continuation: {} bytes", continuationFrame.content().readableBytes());
        listener.onData(continuationFrame.content());
    } else if (frame instanceof PingWebSocketFrame) {
        LOG.trace("WebSocket Client received ping, response with pong");
        ch.write(new PongWebSocketFrame(frame.content()));
    } else if (frame instanceof CloseWebSocketFrame) {
        LOG.trace("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 18
Source File: WebSocketClientHandler.java    From karate with MIT License 4 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            logger.debug("websocket client connected");
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            logger.debug("websocket client connect failed: {}", e.getMessage());
            handshakeFuture.setFailure(e);
        }
        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) {
        if (logger.isTraceEnabled()) {
            logger.trace("websocket received text");
        }
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        listener.onMessage(textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        if (logger.isTraceEnabled()) {
            logger.trace("websocket received pong");
        }
    } else if (frame instanceof CloseWebSocketFrame) {
        logger.debug("websocket closing");
        ch.close();
    } else if (frame instanceof BinaryWebSocketFrame) {
        logger.debug("websocket received binary");
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        ByteBuf buf = binaryFrame.content();
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        listener.onMessage(bytes);
    }
}
 
Example 19
Source File: WebSocketClientHandler.java    From product-ei with Apache License 2.0 4 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        if (logger.isDebugEnabled()) {
            logger.debug("WebSocket Client connected!");
        }
        handshakeFuture.setSuccess();
        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) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        if (logger.isDebugEnabled()) {
            logger.debug("WebSocket Client received text message: " + textFrame.text());
        }
        textReceived = textFrame.text();
    } else if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        bufferReceived = binaryFrame.content().nioBuffer();
        if (logger.isDebugEnabled()) {
            logger.debug("WebSocket Client received  binary message: " + bufferReceived.toString());
        }
    } else if (frame instanceof PongWebSocketFrame) {
        if (logger.isDebugEnabled()) {
            logger.debug("WebSocket Client received pong");
        }
        PongWebSocketFrame pongFrame = (PongWebSocketFrame) frame;
        bufferReceived = pongFrame.content().nioBuffer();
    } else if (frame instanceof CloseWebSocketFrame) {
        if (logger.isDebugEnabled()) {
            logger.debug("WebSocket Client received closing");
        }
        isOpen = false;
    }
    countDownLatch();
}
 
Example 20
Source File: JsonRpcClientNettyWebSocket.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
  Channel ch = ctx.channel();
  if (!handshaker.isHandshakeComplete()) {
    handshaker.finishHandshake(ch, (FullHttpResponse) msg);
    log.debug("{} WebSocket Client connected!", label);
    handshakeFuture.setSuccess();
    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) {
    TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
    if (textFrame.isFinalFragment()) {
      receivedTextMessage(textFrame.text());
    } else {
      partialText.append(textFrame.text());
    }
  } else if (frame instanceof ContinuationWebSocketFrame) {
    ContinuationWebSocketFrame continuationFrame = (ContinuationWebSocketFrame) frame;
    partialText.append(continuationFrame.text());
    if (continuationFrame.isFinalFragment()) {
      receivedTextMessage(partialText.toString());
      partialText.setLength(0);
    }
  } else if (frame instanceof CloseWebSocketFrame) {
    CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) frame;
    log.info("{} Received close frame from server. Will close client! Reason: {}", label,
        closeFrame.reasonText());
  } else {
    log.warn("{} Received frame of type {}. Will be ignored", label,
        frame.getClass().getSimpleName());
  }

}