Search in sources :

Example 1 with WebSocketHttpExchange

use of io.undertow.websockets.spi.WebSocketHttpExchange in project undertow by undertow-io.

the class WebSocketServer method main.

public static void main(final String[] args) {
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(path().addPrefixPath("/myapp", websocket(new WebSocketConnectionCallback() {

        @Override
        public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
            channel.getReceiveSetter().set(new AbstractReceiveListener() {

                @Override
                protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
                    WebSockets.sendText(message.getData(), channel, null);
                }
            });
            channel.resumeReceives();
        }
    })).addPrefixPath("/", resource(new ClassPathResourceManager(WebSocketServer.class.getClassLoader(), WebSocketServer.class.getPackage())).addWelcomeFiles("index.html"))).build();
    server.start();
}
Also used : WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) ClassPathResourceManager(io.undertow.server.handlers.resource.ClassPathResourceManager) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback) Undertow(io.undertow.Undertow) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage)

Example 2 with WebSocketHttpExchange

use of io.undertow.websockets.spi.WebSocketHttpExchange in project undertow by undertow-io.

the class AbstractWebSocketServerTest method testBinary.

@Test
public void testBinary() throws Exception {
    if (getVersion() == WebSocketVersion.V00) {
        // ignore 00 tests for now
        return;
    }
    final AtomicBoolean connected = new AtomicBoolean(false);
    DefaultServer.setRootHandler(new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {

        @Override
        public void onConnect(final WebSocketHttpExchange exchange, final WebSocketChannel channel) {
            connected.set(true);
            channel.getReceiveSetter().set(new AbstractReceiveListener() {

                @Override
                protected void onFullBinaryMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
                    final Pooled<ByteBuffer[]> data = message.getData();
                    WebSockets.sendBinary(data.getResource(), channel, new WebSocketCallback<Void>() {

                        @Override
                        public void complete(WebSocketChannel channel, Void context) {
                            data.close();
                        }

                        @Override
                        public void onError(WebSocketChannel channel, Void context, Throwable throwable) {
                            data.close();
                        }
                    });
                }
            });
            channel.resumeReceives();
        }
    }));
    final FutureResult latch = new FutureResult();
    final byte[] payload = "payload".getBytes();
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + NetworkUtils.formatPossibleIpv6Address(DefaultServer.getHostAddress("default")) + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    client.destroy();
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) Pooled(org.xnio.Pooled) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) WebSocketCallback(io.undertow.websockets.core.WebSocketCallback) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) FrameChecker(io.undertow.websockets.utils.FrameChecker) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) BufferedBinaryMessage(io.undertow.websockets.core.BufferedBinaryMessage) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback) Test(org.junit.Test)

Example 3 with WebSocketHttpExchange

use of io.undertow.websockets.spi.WebSocketHttpExchange in project actframework by actframework.

the class UndertowWebSocketConnectionHandler method handle.

@Override
public void handle(final ActionContext context) {
    if (logger.isTraceEnabled()) {
        logger.trace("handle websocket connection request to %s", context.req().url());
    }
    final UndertowRequest req = (UndertowRequest) context.req();
    HttpServerExchange exchange = req.exchange();
    try {
        Handlers.websocket(new WebSocketConnectionCallback() {

            @Override
            public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
                final WebSocketConnection connection = new UndertowWebSocketConnection(channel, context.session());
                channel.setAttribute("act_conn", connection);
                connectionManager.registerNewConnection(connection, context);
                final WebSocketContext wsCtx = new WebSocketContext(req.url(), connection, connectionManager, context, connectionManager.app());
                if (logger.isTraceEnabled()) {
                    logger.trace("websocket context[%s] created for %s", connection.sessionId(), context.req().url());
                }
                channel.getReceiveSetter().set(new AbstractReceiveListener() {

                    @Override
                    protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
                        WebSocketContext.current(wsCtx);
                        String payload = message.getData();
                        if (logger.isTraceEnabled()) {
                            logger.trace("websocket message received: %s", payload);
                        }
                        wsCtx.messageReceived(payload);
                        invoke(wsCtx);
                    }

                    @Override
                    protected void onClose(WebSocketChannel webSocketChannel, StreamSourceFrameChannel channel) throws IOException {
                        if (logger.isTraceEnabled()) {
                            logger.trace("websocket closed: ", connection.sessionId());
                        }
                        WebSocketContext.current(wsCtx);
                        super.onClose(webSocketChannel, channel);
                        connection.destroy();
                        context.app().eventBus().emit(new WebSocketCloseEvent(wsCtx));
                    }
                });
                channel.resumeReceives();
                Act.eventBus().emit(new WebSocketConnectEvent(wsCtx));
            }
        }).handleRequest(exchange);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw ActErrorResult.of(e);
    }
}
Also used : WebSocketCloseEvent(act.ws.WebSocketCloseEvent) WebSocketConnectEvent(act.ws.WebSocketConnectEvent) WebSocketConnection(act.xio.WebSocketConnection) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) IOException(java.io.IOException) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) IOException(java.io.IOException) WebSocketContext(act.ws.WebSocketContext) HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) StreamSourceFrameChannel(io.undertow.websockets.core.StreamSourceFrameChannel) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback)

Example 4 with WebSocketHttpExchange

use of io.undertow.websockets.spi.WebSocketHttpExchange in project undertow by undertow-io.

the class WebSocketServer method main.

public static void main(final String[] args) {
    // Demonstrates how to use Websocket Protocol Handshake to enable Per-message deflate
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(path().addPrefixPath("/myapp", new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {

        @Override
        public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
            channel.getReceiveSetter().set(new AbstractReceiveListener() {

                @Override
                protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
                    WebSockets.sendText(message.getData(), channel, null);
                }
            });
            channel.resumeReceives();
        }
    }).addExtension(new PerMessageDeflateHandshake(false, 6))).addPrefixPath("/", resource(new ClassPathResourceManager(WebSocketServer.class.getClassLoader(), WebSocketServer.class.getPackage())).addWelcomeFiles("index.html"))).build();
    server.start();
}
Also used : WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) ClassPathResourceManager(io.undertow.server.handlers.resource.ClassPathResourceManager) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback) Undertow(io.undertow.Undertow) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage)

Example 5 with WebSocketHttpExchange

use of io.undertow.websockets.spi.WebSocketHttpExchange in project undertow by undertow-io.

the class AbstractWebSocketServerTest method testText.

@Test
public void testText() throws Exception {
    if (getVersion() == WebSocketVersion.V00) {
        // ignore 00 tests for now
        return;
    }
    final AtomicBoolean connected = new AtomicBoolean(false);
    DefaultServer.setRootHandler(new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {

        @Override
        public void onConnect(final WebSocketHttpExchange exchange, final WebSocketChannel channel) {
            connected.set(true);
            channel.getReceiveSetter().set(new AbstractReceiveListener() {

                @Override
                protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
                    String string = message.getData();
                    if (string.equals("hello")) {
                        WebSockets.sendText("world", channel, null);
                    } else {
                        WebSockets.sendText(string, channel, null);
                    }
                }
            });
            channel.resumeReceives();
        }
    }));
    final FutureResult<?> latch = new FutureResult();
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + NetworkUtils.formatPossibleIpv6Address(DefaultServer.getHostAddress("default")) + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new TextWebSocketFrame(Unpooled.copiedBuffer("hello", CharsetUtil.US_ASCII)), new FrameChecker(TextWebSocketFrame.class, "world".getBytes(CharsetUtil.US_ASCII), latch));
    latch.getIoFuture().get();
    client.destroy();
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) IOException(java.io.IOException) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) FrameChecker(io.undertow.websockets.utils.FrameChecker) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback) Test(org.junit.Test)

Aggregations

WebSocketConnectionCallback (io.undertow.websockets.WebSocketConnectionCallback)9 AbstractReceiveListener (io.undertow.websockets.core.AbstractReceiveListener)9 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)9 WebSocketHttpExchange (io.undertow.websockets.spi.WebSocketHttpExchange)9 BufferedTextMessage (io.undertow.websockets.core.BufferedTextMessage)6 WebSocketProtocolHandshakeHandler (io.undertow.websockets.WebSocketProtocolHandshakeHandler)5 FrameChecker (io.undertow.websockets.utils.FrameChecker)5 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)5 IOException (java.io.IOException)5 URI (java.net.URI)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 Test (org.junit.Test)5 FutureResult (org.xnio.FutureResult)5 Undertow (io.undertow.Undertow)3 ClassPathResourceManager (io.undertow.server.handlers.resource.ClassPathResourceManager)3 BufferedBinaryMessage (io.undertow.websockets.core.BufferedBinaryMessage)3 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)2 WebSocketCallback (io.undertow.websockets.core.WebSocketCallback)2 ByteBuffer (java.nio.ByteBuffer)2 Pooled (org.xnio.Pooled)2