Search in sources :

Example 1 with WebSocketChannel

use of io.undertow.websockets.core.WebSocketChannel in project syncany by syncany.

the class WebServer method onResponse.

@Subscribe
public void onResponse(Response response) {
    try {
        // Send to one or many receivers
        boolean responseWithoutRequest = response.getRequestId() == null || response.getRequestId() <= 0;
        if (responseWithoutRequest) {
            sendBroadcast(response);
        } else {
            HttpServerExchange responseToHttpServerExchange = requestIdRestSocketCache.asMap().get(response.getRequestId());
            WebSocketChannel responseToWebSocketChannel = requestIdWebSocketCache.asMap().get(response.getRequestId());
            if (responseToHttpServerExchange != null) {
                sendTo(responseToHttpServerExchange, response);
            } else if (responseToWebSocketChannel != null) {
                sendTo(responseToWebSocketChannel, response);
            } else {
                logger.log(Level.WARNING, "Cannot send message, because request ID in response is unknown or timed out." + response);
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Cannot send response.", e);
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) Subscribe(com.google.common.eventbus.Subscribe)

Example 2 with WebSocketChannel

use of io.undertow.websockets.core.WebSocketChannel in project syncany by syncany.

the class InternalWebSocketHandler method onConnect.

@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    logger.log(Level.INFO, "Connecting to websocket server.");
    // Validate origin header (security!)
    String originHeader = exchange.getRequestHeader("Origin");
    if (!allowedOriginHeader(originHeader)) {
        logger.log(Level.INFO, channel.toString() + " disconnected due to invalid origin header: " + originHeader);
        exchange.close();
    } else {
        logger.log(Level.INFO, "Valid origin header, setting up connection.");
        channel.getReceiveSetter().set(new AbstractReceiveListener() {

            @Override
            protected void onFullTextMessage(WebSocketChannel clientChannel, BufferedTextMessage message) {
                handleMessage(clientChannel, message.getData());
            }

            @Override
            protected void onError(WebSocketChannel webSocketChannel, Throwable error) {
                logger.log(Level.INFO, "Server error : " + error.toString());
            }

            @Override
            protected void onClose(WebSocketChannel clientChannel, StreamSourceFrameChannel streamSourceChannel) throws IOException {
                logger.log(Level.INFO, clientChannel.toString() + " disconnected");
                daemonWebServer.removeClientChannel(clientChannel);
            }
        });
        logger.log(Level.INFO, "A new client (" + channel.hashCode() + ") connected using format " + requestFormatType);
        daemonWebServer.addClientChannel(channel, requestFormatType);
        channel.resumeReceives();
    }
}
Also used : StreamSourceFrameChannel(io.undertow.websockets.core.StreamSourceFrameChannel) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) IOException(java.io.IOException) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage)

Example 3 with WebSocketChannel

use of io.undertow.websockets.core.WebSocketChannel in project undertow by undertow-io.

the class DebugExtensionsListener method onFullCloseMessage.

@Override
protected void onFullCloseMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
    WebSocketLogger.EXTENSION_LOGGER.info("onFullCloseMessage() ");
    Pooled<ByteBuffer[]> pooled = message.getData();
    try {
        ByteBuffer[] data = pooled.getResource();
        /*
            Empty messages should be closed as NORMAL_CLOSURE.
         */
        if (data.length == 1 || !data[0].hasRemaining()) {
            for (WebSocketChannel peerChannel : channel.getPeerConnections()) {
                WebSockets.sendClose(CloseMessage.NORMAL_CLOSURE, "", peerChannel, null);
            }
        } else {
            for (WebSocketChannel peerChannel : channel.getPeerConnections()) {
                WebSockets.sendClose(data, peerChannel, null);
            }
        }
    } finally {
        pooled.close();
    }
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) ByteBuffer(java.nio.ByteBuffer)

Example 4 with WebSocketChannel

use of io.undertow.websockets.core.WebSocketChannel in project undertow by undertow-io.

the class DebugExtensionsListener method onFullPingMessage.

@Override
protected void onFullPingMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
    WebSocketLogger.EXTENSION_LOGGER.info("onFullPingMessage() ");
    ByteBuffer[] data = message.getData().getResource();
    for (WebSocketChannel peerChannel : channel.getPeerConnections()) {
        WebSockets.sendPong(data, peerChannel, null);
    }
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) ByteBuffer(java.nio.ByteBuffer)

Example 5 with WebSocketChannel

use of io.undertow.websockets.core.WebSocketChannel in project undertow by undertow-io.

the class WebSocketExtensionBasicTestCase method testExtensionsHeaders.

/**
     * Simulate an extensions request.
     *
     * <pre>{@code

    GET / HTTP/1.1
    User-Agent: AutobahnTestSuite/0.7.0-0.9.0
    Host: localhost:7777
    Upgrade: WebSocket
    Connection: Upgrade
    Pragma: no-cache
    Cache-Control: no-cache
    Sec-WebSocket-Key: pRAuwtkO0SUKzufqA2g+ig==
    Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; client_max_window_bits
    Sec-WebSocket-Version: 13

     * }
     * </pre>
     */
@Test
public void testExtensionsHeaders() throws Exception {
    XnioWorker client;
    Xnio xnio = Xnio.getInstance(WebSocketExtensionBasicTestCase.class.getClassLoader());
    client = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, 2).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
    WebSocketProtocolHandshakeHandler handler = webSocketDebugHandler().addExtension(new PerMessageDeflateHandshake());
    DebugExtensionsHeaderHandler debug = new DebugExtensionsHeaderHandler(handler);
    DefaultServer.setRootHandler(path().addPrefixPath("/", debug));
    final String SEC_WEBSOCKET_EXTENSIONS = "permessage-deflate; client_no_context_takeover; client_max_window_bits";
    // List format
    final String SEC_WEBSOCKET_EXTENSIONS_EXPECTED = "[permessage-deflate; client_no_context_takeover]";
    List<WebSocketExtension> extensions = WebSocketExtension.parse(SEC_WEBSOCKET_EXTENSIONS);
    final WebSocketClientNegotiation negotiation = new WebSocketClientNegotiation(null, extensions);
    Set<ExtensionHandshake> extensionHandshakes = new HashSet<>();
    extensionHandshakes.add(new PerMessageDeflateHandshake(true));
    final WebSocketChannel clientChannel = WebSocketClient.connect(client, null, DefaultServer.getBufferPool(), OptionMap.EMPTY, new URI(DefaultServer.getDefaultServerURL()), WebSocketVersion.V13, negotiation, extensionHandshakes).get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    clientChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
            String data = message.getData();
            WebSocketLogger.ROOT_LOGGER.info("onFullTextMessage - Client - Received: " + data.getBytes().length + " bytes . Data: " + data);
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onFullCloseMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
            message.getData().close();
            WebSocketLogger.ROOT_LOGGER.info("onFullCloseMessage");
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            WebSocketLogger.ROOT_LOGGER.info("onError");
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    clientChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = clientChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello, World!").setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("Hello, World!", result.get());
    clientChannel.sendClose();
    client.shutdown();
    Assert.assertEquals(SEC_WEBSOCKET_EXTENSIONS_EXPECTED, debug.getResponseExtensions().toString());
}
Also used : XnioWorker(org.xnio.XnioWorker) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) Xnio(org.xnio.Xnio) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) BufferedBinaryMessage(io.undertow.websockets.core.BufferedBinaryMessage) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) HashSet(java.util.HashSet) WebSocketExtension(io.undertow.websockets.WebSocketExtension) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) Test(org.junit.Test)

Aggregations

WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)38 AbstractReceiveListener (io.undertow.websockets.core.AbstractReceiveListener)18 IOException (java.io.IOException)18 URI (java.net.URI)17 Test (org.junit.Test)17 BufferedTextMessage (io.undertow.websockets.core.BufferedTextMessage)16 BufferedBinaryMessage (io.undertow.websockets.core.BufferedBinaryMessage)10 CountDownLatch (java.util.concurrent.CountDownLatch)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 StringWriteChannelListener (io.undertow.util.StringWriteChannelListener)7 WebSocketConnectionCallback (io.undertow.websockets.WebSocketConnectionCallback)7 WebSocketExtension (io.undertow.websockets.WebSocketExtension)7 WebSocketProtocolHandshakeHandler (io.undertow.websockets.WebSocketProtocolHandshakeHandler)7 StreamSinkFrameChannel (io.undertow.websockets.core.StreamSinkFrameChannel)7 WebSocketHttpExchange (io.undertow.websockets.spi.WebSocketHttpExchange)7 WebSocketClientNegotiation (io.undertow.websockets.client.WebSocketClientNegotiation)6 HttpServerExchange (io.undertow.server.HttpServerExchange)5 ExtensionHandshake (io.undertow.websockets.extensions.ExtensionHandshake)5 ByteBuffer (java.nio.ByteBuffer)5 HttpUpgradeListener (io.undertow.server.HttpUpgradeListener)4