下面列出了怎么用 io.netty.handler.codec.http.websocketx.WebSocketHandshakeException 的API类实例代码及写法,或者点击链接到github查看源代码。
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) + ')');
}
}
@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();
}
}
@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();
}
}
@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();
}
}
@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();
}
}
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();
}
@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));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof WebSocketHandshakeException) {
sendBadRequestAndClose(ctx, cause.getMessage());
} else {
ctx.close();
}
}
@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();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof WebSocketHandshakeException) {
sendBadRequestAndClose(ctx, cause.getMessage());
} else {
ctx.close();
}
}
@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);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (cause instanceof WebSocketHandshakeException) {
log.debug("Web Socket Handshake Exception.", cause);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (cause instanceof WebSocketHandshakeException) {
log.debug("Web Socket Handshake Exception.", cause);
}
}