Search in sources :

Example 6 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project netty-socketio by mrniko.

the class EncoderHandler method handleWebsocket.

private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx, ChannelPromise promise) throws IOException {
    while (true) {
        Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());
        Packet packet = queue.poll();
        if (packet == null) {
            promise.trySuccess();
            break;
        }
        final ByteBuf out = encoder.allocateBuffer(ctx.alloc());
        encoder.encodePacket(packet, out, ctx.alloc(), true);
        WebSocketFrame res = new TextWebSocketFrame(out);
        if (log.isTraceEnabled()) {
            log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
        }
        if (out.isReadable()) {
            if (!promise.isDone()) {
                ctx.channel().writeAndFlush(res, promise);
            } else {
                ctx.channel().writeAndFlush(res);
            }
        } else {
            promise.trySuccess();
            out.release();
        }
        for (ByteBuf buf : packet.getAttachments()) {
            ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc());
            outBuf.writeByte(4);
            outBuf.writeBytes(buf);
            if (log.isTraceEnabled()) {
                log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId());
            }
            ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf));
        }
    }
}
Also used : Packet(com.corundumstudio.socketio.protocol.Packet) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) ByteBuf(io.netty.buffer.ByteBuf)

Example 7 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project undertow by undertow-io.

the class WebSocketTestClient method destroy.

/**
     * Destroy the client and also close open connections if any exist
     */
public void destroy() {
    if (!closed) {
        final CountDownLatch latch = new CountDownLatch(1);
        send(new CloseWebSocketFrame(), new FrameListener() {

            @Override
            public void onFrame(WebSocketFrame frame) {
                latch.countDown();
            }

            @Override
            public void onError(Throwable t) {
                latch.countDown();
            }
        });
        try {
            latch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    //bootstrap.releaseExternalResources();
    if (ch != null) {
        ch.close().syncUninterruptibly();
    }
    try {
        bootstrap.group().shutdownGracefully(0, 1, TimeUnit.SECONDS).get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutionException(java.util.concurrent.ExecutionException)

Example 8 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project async-http-client by AsyncHttpClient.

the class WebSocketHandler method handleRead.

@Override
public void handleRead(Channel channel, NettyResponseFuture<?> future, Object e) throws Exception {
    if (e instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e;
        if (logger.isDebugEnabled()) {
            HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
            logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
        }
        WebSocketUpgradeHandler handler = (WebSocketUpgradeHandler) future.getAsyncHandler();
        HttpResponseStatus status = new NettyResponseStatus(future.getUri(), response, channel);
        HttpResponseHeaders responseHeaders = new HttpResponseHeaders(response.headers());
        if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
            switch(handler.onStatusReceived(status)) {
                case CONTINUE:
                    upgrade(channel, future, handler, response, responseHeaders);
                    break;
                default:
                    abort(channel, future, handler, status);
            }
        }
    } else if (e instanceof WebSocketFrame) {
        final WebSocketFrame frame = (WebSocketFrame) e;
        WebSocketUpgradeHandler handler = (WebSocketUpgradeHandler) future.getAsyncHandler();
        NettyWebSocket webSocket = handler.onCompleted();
        // retain because we might buffer the frame
        if (webSocket.isReady()) {
            webSocket.handleFrame(frame);
        } else {
            // WebSocket hasn't been open yet, but upgrading the pipeline triggered a read and a frame was sent along the HTTP upgrade response
            // as we want to keep sequential order (but can't notify user of open before upgrading so he doesn't to try send immediately), we have to buffer
            webSocket.bufferFrame(frame);
        }
    } else if (!(e instanceof LastHttpContent)) {
        // ignore, end of handshake response
        logger.error("Invalid message {}", e);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) NettyResponseStatus(org.asynchttpclient.netty.NettyResponseStatus) HttpResponseHeaders(org.asynchttpclient.HttpResponseHeaders) HttpResponseStatus(org.asynchttpclient.HttpResponseStatus) NettyWebSocket(org.asynchttpclient.netty.ws.NettyWebSocket) HttpResponse(io.netty.handler.codec.http.HttpResponse) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) WebSocketUpgradeHandler(org.asynchttpclient.ws.WebSocketUpgradeHandler) LastHttpContent(io.netty.handler.codec.http.LastHttpContent)

Aggregations

WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)8 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)5 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)4 ByteBuf (io.netty.buffer.ByteBuf)3 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)3 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)2 Channel (io.netty.channel.Channel)2 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)2 CodecException (io.netty.handler.codec.CodecException)2 ContinuationWebSocketFrame (io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame)2 ExecutionException (java.util.concurrent.ExecutionException)2 Packet (com.corundumstudio.socketio.protocol.Packet)1 Bootstrap (io.netty.bootstrap.Bootstrap)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelPipeline (io.netty.channel.ChannelPipeline)1 EventLoopGroup (io.netty.channel.EventLoopGroup)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1