Search in sources :

Example 1 with WebSocketHandshakeException

use of io.netty.handler.codec.http.websocketx.WebSocketHandshakeException in project reactor-netty by reactor.

the class HttpClientWSOperations method onInboundNext.

@Override
@SuppressWarnings("unchecked")
public void onInboundNext(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof FullHttpResponse) {
        started = true;
        channel().pipeline().remove(HttpObjectAggregator.class);
        FullHttpResponse response = (FullHttpResponse) msg;
        setNettyResponse(response);
        if (checkResponseCode(response)) {
            try {
                if (!handshaker.isHandshakeComplete()) {
                    handshaker.finishHandshake(channel(), response);
                }
            } catch (WebSocketHandshakeException wshe) {
                if (serverError) {
                    onInboundError(wshe);
                    return;
                }
            } finally {
                // Release unused content (101 status)
                response.content().release();
            }
            parentContext().fireContextActive(this);
            handshakerResult.trySuccess();
        }
        return;
    }
    if (msg instanceof PingWebSocketFrame) {
        channel().writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) msg).content()));
        ctx.read();
        return;
    }
    if (msg instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) msg).isFinalFragment()) {
        if (log.isDebugEnabled()) {
            log.debug("CloseWebSocketFrame detected. Closing Websocket");
        }
        CloseWebSocketFrame close = (CloseWebSocketFrame) msg;
        sendClose(new CloseWebSocketFrame(true, close.rsv(), close.content()));
    } else {
        super.onInboundNext(ctx, msg);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 2 with WebSocketHandshakeException

use of io.netty.handler.codec.http.websocketx.WebSocketHandshakeException in project vert.x by eclipse.

the class WebsocketTest method doTestClientWebsocketConnectionCloseOnBadResponse.

private void doTestClientWebsocketConnectionCloseOnBadResponse(boolean keepAliveInOptions) throws Throwable {
    final Exception serverGotCloseException = new Exception();
    netServer = vertx.createNetServer().connectHandler(sock -> {
        final Buffer fullReq = Buffer.buffer(230);
        sock.handler(b -> {
            fullReq.appendBuffer(b);
            String reqPart = b.toString();
            if (fullReq.toString().contains("\r\n\r\n")) {
                try {
                    String content = "0123456789";
                    content = content + content;
                    content = content + content + content + content + content;
                    String resp = "HTTP/1.1 200 OK\r\n";
                    if (keepAliveInOptions) {
                        resp += "Connection: close\r\n";
                    }
                    resp += "Content-Length: 100\r\n\r\n" + content;
                    sock.write(Buffer.buffer(resp.getBytes("ASCII")));
                } catch (UnsupportedEncodingException e) {
                    addResult(e);
                }
            }
        });
        sock.closeHandler(v -> {
            addResult(serverGotCloseException);
        });
    }).listen(ar -> {
        if (ar.failed()) {
            addResult(ar.cause());
            return;
        }
        NetServer server = ar.result();
        int port = server.actualPort();
        HttpClientOptions opts = new HttpClientOptions().setKeepAlive(keepAliveInOptions);
        client.close();
        client = vertx.createHttpClient(opts).websocket(port, "localhost", "/", ws -> {
            addResult(new AssertionError("Websocket unexpectedly connected"));
            ws.close();
        }, t -> {
            addResult(t);
        });
    });
    boolean serverGotClose = false;
    boolean clientGotCorrectException = false;
    while (!serverGotClose || !clientGotCorrectException) {
        Throwable result = resultQueue.poll(20, TimeUnit.SECONDS);
        if (result == null) {
            throw new AssertionError("Timed out waiting for expected state, current: serverGotClose = " + serverGotClose + ", clientGotCorrectException = " + clientGotCorrectException);
        } else if (result == serverGotCloseException) {
            serverGotClose = true;
        } else if (result instanceof WebSocketHandshakeException && result.getMessage().equals("Websocket connection attempt returned HTTP status code 200")) {
            clientGotCorrectException = true;
        } else {
            throw result;
        }
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Arrays(java.util.Arrays) MessageDigest(java.security.MessageDigest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestUtils(io.vertx.test.core.TestUtils) Map(java.util.Map) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) Consumer(java.util.function.Consumer) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Handler(io.vertx.core.Handler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NetServer(io.vertx.core.net.NetServer) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 3 with WebSocketHandshakeException

use of io.netty.handler.codec.http.websocketx.WebSocketHandshakeException in project netty by netty.

the class WebSocketClientHandler method channelRead0.

@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();
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) Channel(io.netty.channel.Channel) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException)

Example 4 with WebSocketHandshakeException

use of io.netty.handler.codec.http.websocketx.WebSocketHandshakeException in project vert.x by eclipse.

the class WebSocketHandshakeInboundHandler method handshakeComplete.

private Future<HeadersAdaptor> handshakeComplete(FullHttpResponse response) {
    int sc = response.status().code();
    if (sc != 101) {
        String msg = "WebSocket upgrade failure: " + sc;
        ByteBuf content = response.content();
        if (content != null && content.readableBytes() > 0) {
            msg += " (" + content.toString(StandardCharsets.UTF_8) + ")";
        }
        UpgradeRejectedException failure = new UpgradeRejectedException(msg, sc);
        return Future.failedFuture(failure);
    } else {
        try {
            handshaker.finishHandshake(chctx.channel(), response);
            return Future.succeededFuture(new HeadersAdaptor(response.headers()));
        } catch (WebSocketHandshakeException e) {
            return Future.failedFuture(e);
        }
    }
}
Also used : HeadersAdaptor(io.vertx.core.http.impl.headers.HeadersAdaptor) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) ByteBuf(io.netty.buffer.ByteBuf) UpgradeRejectedException(io.vertx.core.http.UpgradeRejectedException)

Aggregations

WebSocketHandshakeException (io.netty.handler.codec.http.websocketx.WebSocketHandshakeException)4 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)2 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)2 PongWebSocketFrame (io.netty.handler.codec.http.websocketx.PongWebSocketFrame)2 ByteBuf (io.netty.buffer.ByteBuf)1 Channel (io.netty.channel.Channel)1 PingWebSocketFrame (io.netty.handler.codec.http.websocketx.PingWebSocketFrame)1 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)1 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)1 AbstractVerticle (io.vertx.core.AbstractVerticle)1 AsyncResult (io.vertx.core.AsyncResult)1 Context (io.vertx.core.Context)1 DeploymentOptions (io.vertx.core.DeploymentOptions)1 Future (io.vertx.core.Future)1 Handler (io.vertx.core.Handler)1 Vertx (io.vertx.core.Vertx)1 Buffer (io.vertx.core.buffer.Buffer)1 io.vertx.core.http (io.vertx.core.http)1 UpgradeRejectedException (io.vertx.core.http.UpgradeRejectedException)1 HeadersAdaptor (io.vertx.core.http.impl.headers.HeadersAdaptor)1