Search in sources :

Example 1 with WebSocketClientNegotiation

use of io.undertow.websockets.client.WebSocketClientNegotiation 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)

Example 2 with WebSocketClientNegotiation

use of io.undertow.websockets.client.WebSocketClientNegotiation in project undertow by undertow-io.

the class ServerWebSocketContainer method connectToServer.

public Session connectToServer(final Endpoint endpointInstance, final ClientEndpointConfig config, WebSocketClient.ConnectionBuilder connectionBuilder) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ClientEndpointConfig cec = config != null ? config : ClientEndpointConfig.Builder.create().build();
    WebSocketClientNegotiation clientNegotiation = connectionBuilder.getClientNegotiation();
    IoFuture<WebSocketChannel> session = connectionBuilder.connect();
    Number timeout = (Number) cec.getUserProperties().get(TIMEOUT);
    if (session.await(timeout == null ? DEFAULT_WEB_SOCKET_TIMEOUT_SECONDS : timeout.intValue(), TimeUnit.SECONDS) == IoFuture.Status.WAITING) {
        //add a notifier to close the channel if the connection actually completes
        session.cancel();
        session.addNotifier(new IoFuture.HandlingNotifier<WebSocketChannel, Object>() {

            @Override
            public void handleDone(WebSocketChannel data, Object attachment) {
                IoUtils.safeClose(data);
            }
        }, null);
        throw JsrWebSocketMessages.MESSAGES.connectionTimedOut();
    }
    WebSocketChannel channel;
    try {
        channel = session.get();
    } catch (UpgradeFailedException e) {
        throw new DeploymentException(e.getMessage(), e);
    }
    EndpointSessionHandler sessionHandler = new EndpointSessionHandler(this);
    final List<Extension> extensions = new ArrayList<>();
    final Map<String, Extension> extMap = new HashMap<>();
    for (Extension ext : cec.getExtensions()) {
        extMap.put(ext.getName(), ext);
    }
    for (WebSocketExtension e : clientNegotiation.getSelectedExtensions()) {
        Extension ext = extMap.get(e.getName());
        if (ext == null) {
            throw JsrWebSocketMessages.MESSAGES.extensionWasNotPresentInClientHandshake(e.getName(), clientNegotiation.getSupportedExtensions());
        }
        extensions.add(ExtensionImpl.create(e));
    }
    ConfiguredClientEndpoint configured = clientEndpoints.get(endpointInstance.getClass());
    if (configured == null) {
        synchronized (clientEndpoints) {
            configured = clientEndpoints.get(endpointInstance.getClass());
            if (configured == null) {
                clientEndpoints.put(endpointInstance.getClass(), configured = new ConfiguredClientEndpoint());
            }
        }
    }
    EncodingFactory encodingFactory = EncodingFactory.createFactory(classIntrospecter, cec.getDecoders(), cec.getEncoders());
    UndertowSession undertowSession = new UndertowSession(channel, connectionBuilder.getUri(), Collections.<String, String>emptyMap(), Collections.<String, List<String>>emptyMap(), sessionHandler, null, new ImmediateInstanceHandle<>(endpointInstance), cec, connectionBuilder.getUri().getQuery(), encodingFactory.createEncoding(cec), configured, clientNegotiation.getSelectedSubProtocol(), extensions, connectionBuilder);
    endpointInstance.onOpen(undertowSession, cec);
    channel.resumeReceives();
    return undertowSession;
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) WebSocketExtension(io.undertow.websockets.WebSocketExtension) HashMap(java.util.HashMap) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) ArrayList(java.util.ArrayList) IoFuture(org.xnio.IoFuture) WebSocketExtension(io.undertow.websockets.WebSocketExtension) Extension(javax.websocket.Extension) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) UpgradeFailedException(org.xnio.http.UpgradeFailedException) DeploymentException(javax.websocket.DeploymentException) ClientEndpointConfig(javax.websocket.ClientEndpointConfig)

Example 3 with WebSocketClientNegotiation

use of io.undertow.websockets.client.WebSocketClientNegotiation in project undertow by undertow-io.

the class ServerWebSocketContainer method connectToServerInternal.

private Session connectToServerInternal(final Endpoint endpointInstance, XnioSsl ssl, final ConfiguredClientEndpoint cec, final URI path) throws DeploymentException, IOException {
    //in theory we should not be able to connect until the deployment is complete, but the definition of when a deployment is complete is a bit nebulous.
    WebSocketClientNegotiation clientNegotiation = new ClientNegotiation(cec.getConfig().getPreferredSubprotocols(), toExtensionList(cec.getConfig().getExtensions()), cec.getConfig());
    WebSocketClient.ConnectionBuilder connectionBuilder = WebSocketClient.connectionBuilder(xnioWorker, bufferPool, path).setSsl(ssl).setBindAddress(clientBindAddress).setClientNegotiation(clientNegotiation);
    return connectToServerInternal(endpointInstance, cec, connectionBuilder);
}
Also used : WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) WebSocketClient(io.undertow.websockets.client.WebSocketClient) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation)

Example 4 with WebSocketClientNegotiation

use of io.undertow.websockets.client.WebSocketClientNegotiation in project undertow by undertow-io.

the class ServerWebSocketContainer method connectToServer.

@Override
public Session connectToServer(final Endpoint endpointInstance, final ClientEndpointConfig config, final URI path) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ClientEndpointConfig cec = config != null ? config : ClientEndpointConfig.Builder.create().build();
    XnioSsl ssl = null;
    for (WebsocketClientSslProvider provider : clientSslProviders) {
        ssl = provider.getSsl(xnioWorker, endpointInstance, cec, path);
        if (ssl != null) {
            break;
        }
    }
    //in theory we should not be able to connect until the deployment is complete, but the definition of when a deployment is complete is a bit nebulous.
    WebSocketClientNegotiation clientNegotiation = new ClientNegotiation(cec.getPreferredSubprotocols(), toExtensionList(cec.getExtensions()), cec);
    WebSocketClient.ConnectionBuilder connectionBuilder = WebSocketClient.connectionBuilder(xnioWorker, bufferPool, path).setSsl(ssl).setBindAddress(clientBindAddress).setClientNegotiation(clientNegotiation);
    return connectToServer(endpointInstance, config, connectionBuilder);
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) XnioSsl(org.xnio.ssl.XnioSsl) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) WebSocketClient(io.undertow.websockets.client.WebSocketClient) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation)

Example 5 with WebSocketClientNegotiation

use of io.undertow.websockets.client.WebSocketClientNegotiation in project undertow by undertow-io.

the class JsrWebsocketExtensionTestCase method testLongTextMessage.

@Test
public void testLongTextMessage() throws Exception {
    final String SEC_WEBSOCKET_EXTENSIONS = "permessage-deflate; client_no_context_takeover; client_max_window_bits";
    List<WebSocketExtension> extensionsList = WebSocketExtension.parse(SEC_WEBSOCKET_EXTENSIONS);
    final WebSocketClientNegotiation negotiation = new WebSocketClientNegotiation(null, extensionsList);
    Set<ExtensionHandshake> extensionHandshakes = new HashSet<>();
    extensionHandshakes.add(new PerMessageDeflateHandshake(true));
    final WebSocketChannel clientChannel = WebSocketClient.connect(DefaultServer.getWorker(), null, DefaultServer.getBufferPool(), OptionMap.EMPTY, new URI(DefaultServer.getDefaultServerURL()), WebSocketVersion.V13, negotiation, extensionHandshakes).get();
    final LinkedBlockingDeque<String> resultQueue = new LinkedBlockingDeque<>();
    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.");
            resultQueue.addLast(data);
        }

        @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();
            resultQueue.add("FAILED " + error);
        }
    });
    clientChannel.resumeReceives();
    int LONG_MSG = 125 * 1024;
    StringBuilder longMsg = new StringBuilder(LONG_MSG);
    for (int i = 0; i < LONG_MSG; i++) {
        longMsg.append(Integer.toString(i).charAt(0));
    }
    String message = longMsg.toString();
    for (int j = 0; j < MSG_COUNT; ++j) {
        WebSockets.sendTextBlocking(message, clientChannel);
        String res = resultQueue.poll(3, TimeUnit.SECONDS);
        Assert.assertEquals(message, res);
    }
    clientChannel.sendClose();
}
Also used : WebSocketExtension(io.undertow.websockets.WebSocketExtension) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) IOException(java.io.IOException) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) AutobahnAnnotatedEndpoint(io.undertow.websockets.jsr.test.autobahn.AutobahnAnnotatedEndpoint) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) ExtensionHandshake(io.undertow.websockets.extensions.ExtensionHandshake) BufferedBinaryMessage(io.undertow.websockets.core.BufferedBinaryMessage) HashSet(java.util.HashSet) Test(org.junit.Test) BinaryEndpointTest(io.undertow.websockets.jsr.test.BinaryEndpointTest)

Aggregations

WebSocketClientNegotiation (io.undertow.websockets.client.WebSocketClientNegotiation)8 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)6 WebSocketExtension (io.undertow.websockets.WebSocketExtension)5 AbstractReceiveListener (io.undertow.websockets.core.AbstractReceiveListener)5 BufferedBinaryMessage (io.undertow.websockets.core.BufferedBinaryMessage)5 BufferedTextMessage (io.undertow.websockets.core.BufferedTextMessage)5 IOException (java.io.IOException)5 URI (java.net.URI)5 Test (org.junit.Test)5 HashSet (java.util.HashSet)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 StringWriteChannelListener (io.undertow.util.StringWriteChannelListener)3 WebSocketProtocolHandshakeHandler (io.undertow.websockets.WebSocketProtocolHandshakeHandler)3 StreamSinkFrameChannel (io.undertow.websockets.core.StreamSinkFrameChannel)3 Xnio (org.xnio.Xnio)3 XnioWorker (org.xnio.XnioWorker)3 WebSocketClient (io.undertow.websockets.client.WebSocketClient)2 ExtensionHandshake (io.undertow.websockets.extensions.ExtensionHandshake)2 PerMessageDeflateHandshake (io.undertow.websockets.extensions.PerMessageDeflateHandshake)2