io.netty.handler.codec.http.websocketx.WebSocketHandshakeException Java Examples

The following examples show how to use io.netty.handler.codec.http.websocketx.WebSocketHandshakeException. 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: 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 #2
Source File: NettyWebSocketClient.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext context, Object message) {
  Channel channel = context.channel();
  if (message instanceof FullHttpResponse) {
    checkState(!handshaker.isHandshakeComplete());
    try {
      handshaker.finishHandshake(channel, (FullHttpResponse) message);
      delegate.onOpen();
    } catch (WebSocketHandshakeException e) {
      delegate.onError(e);
    }
  } else if (message instanceof TextWebSocketFrame) {
    delegate.onMessage(((TextWebSocketFrame) message).text());
  } else {
    checkState(message instanceof CloseWebSocketFrame);
    delegate.onClose();
  }
}
 
Example #3
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 #4
Source File: PoloniexWSSClientRouter.java    From poloniex-api-java with MIT License 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);
            running = true;
            LOG.trace("WebSocket Client connected!");
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            LOG.trace("WebSocket Client failed to connect");
            running = false;
            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;
        LOG.trace("WebSocket Client received message: " + textFrame.text());
        List results = this.gson.fromJson(textFrame.text(), List.class);
        this.subscriptions.getOrDefault(results.get(0), this.defaultSubscriptionMessageHandler).handle(textFrame.text());
        
    } else if (frame instanceof CloseWebSocketFrame) {
        LOG.trace("WebSocket Client received closing");
        running = false;
        ch.close();
    }

}
 
Example #5
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 #6
Source File: WebsocketClientOperationsTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
private void failOnClientServerError(
		int serverStatus, String serverSubprotocol, String clientSubprotocol) {
	DisposableServer httpServer =
			HttpServer.create()
			          .port(0)
			          .route(routes ->
			              routes.post("/login", (req, res) -> res.status(serverStatus).sendHeaders())
			                    .get("/ws", (req, res) -> {
			                        int token = Integer.parseInt(req.requestHeaders().get("Authorization"));
			                        if (token >= 400) {
			                            return res.status(token).send();
			                        }
			                        return res.sendWebsocket((i, o) -> o.sendString(Mono.just("test")),
			                                WebsocketServerSpec.builder().protocols(serverSubprotocol).build());
			                    }))
			          .wiretap(true)
			          .bindNow();

	Flux<String> response =
			HttpClient.create()
			          .port(httpServer.port())
			          .wiretap(true)
			          .headersWhen(h -> login(httpServer.port()).map(token -> h.set("Authorization", token)))
			          .websocket(WebsocketClientSpec.builder().protocols(clientSubprotocol).build())
			          .uri("/ws")
			          .handle((i, o) -> i.receive().asString())
			          .log()
			          .switchIfEmpty(Mono.error(new Exception()));

	StepVerifier.create(response)
	            .expectError(WebSocketHandshakeException.class)
	            .verify();

	httpServer.disposeNow();
}
 
Example #7
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void serverWebSocketFailed() {
	httpServer =
			HttpServer.create()
			          .port(0)
			          .handle((in, out) -> {
			              if (!in.requestHeaders().contains("Authorization")) {
			                  return out.status(401);
			              } else {
			                  return out.sendWebsocket((i, o) -> o.sendString(Mono.just("test")));
			              }
			          })
			          .wiretap(true)
			          .bindNow();

	Mono<String> res =
			HttpClient.create()
			          .port(httpServer.port())
			          .websocket()
			          .uri("/test")
			          .handle((in, out) -> in.receive().aggregate().asString())
			          .next();

	StepVerifier.create(res)
	            .expectError(WebSocketHandshakeException.class)
	            .verify(Duration.ofSeconds(30));
}
 
Example #8
Source File: WampServerWebsocketHandler.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (cause instanceof WebSocketHandshakeException) {
        sendBadRequestAndClose(ctx, cause.getMessage());
    } else {
        ctx.close();
    }
}
 
Example #9
Source File: WebSocketClientHandler.java    From rsocket-java 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 #10
Source File: WampServerWebsocketHandler.java    From jawampa with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (cause instanceof WebSocketHandshakeException) {
        sendBadRequestAndClose(ctx, cause.getMessage());
    } else {
        ctx.close();
    }
}
 
Example #11
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 #12
Source File: WSHandler.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (cause instanceof WebSocketHandshakeException) {
        log.debug("Web Socket Handshake Exception.", cause);
    }
}
 
Example #13
Source File: WSMessageDecoder.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (cause instanceof WebSocketHandshakeException) {
        log.debug("Web Socket Handshake Exception.", cause);
    }
}