Search in sources :

Example 11 with WebSocketChannel

use of io.undertow.websockets.core.WebSocketChannel 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 12 with WebSocketChannel

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

the class ServerWebSocketContainer method connectToServerInternal.

private Session connectToServerInternal(final Endpoint endpointInstance, final ConfiguredClientEndpoint cec, WebSocketClient.ConnectionBuilder connectionBuilder) throws DeploymentException, IOException {
    IoFuture<WebSocketChannel> session = connectionBuilder.connect();
    Number timeout = (Number) cec.getConfig().getUserProperties().get(TIMEOUT);
    IoFuture.Status result = session.await(timeout == null ? DEFAULT_WEB_SOCKET_TIMEOUT_SECONDS : timeout.intValue(), TimeUnit.SECONDS);
    if (result == 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.getConfig().getExtensions()) {
        extMap.put(ext.getName(), ext);
    }
    String subProtocol = null;
    if (connectionBuilder.getClientNegotiation() != null) {
        for (WebSocketExtension e : connectionBuilder.getClientNegotiation().getSelectedExtensions()) {
            Extension ext = extMap.get(e.getName());
            if (ext == null) {
                throw JsrWebSocketMessages.MESSAGES.extensionWasNotPresentInClientHandshake(e.getName(), connectionBuilder.getClientNegotiation().getSupportedExtensions());
            }
            extensions.add(ExtensionImpl.create(e));
        }
        subProtocol = connectionBuilder.getClientNegotiation().getSelectedSubProtocol();
    }
    UndertowSession undertowSession = new UndertowSession(channel, connectionBuilder.getUri(), Collections.<String, String>emptyMap(), Collections.<String, List<String>>emptyMap(), sessionHandler, null, new ImmediateInstanceHandle<>(endpointInstance), cec.getConfig(), connectionBuilder.getUri().getQuery(), cec.getEncodingFactory().createEncoding(cec.getConfig()), cec, subProtocol, extensions, connectionBuilder);
    endpointInstance.onOpen(undertowSession, cec.getConfig());
    channel.resumeReceives();
    return undertowSession;
}
Also used : 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) UpgradeFailedException(org.xnio.http.UpgradeFailedException) DeploymentException(javax.websocket.DeploymentException)

Example 13 with WebSocketChannel

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

the class WebSocketServlet method doGet.

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp, peerConnections);
    Handshake handshaker = null;
    for (Handshake method : handshakes) {
        if (method.matches(facade)) {
            handshaker = method;
            break;
        }
    }
    if (handshaker == null) {
        UndertowLogger.REQUEST_LOGGER.debug("Could not find hand shaker for web socket request");
        resp.sendError(StatusCodes.BAD_REQUEST);
        return;
    }
    final Handshake selected = handshaker;
    facade.upgradeChannel(new HttpUpgradeListener() {

        @Override
        public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
            WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
            peerConnections.add(channel);
            callback.onConnect(facade, channel);
        }
    });
    handshaker.handshake(facade);
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener) StreamConnection(org.xnio.StreamConnection) Hybi07Handshake(io.undertow.websockets.core.protocol.version07.Hybi07Handshake) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake) Hybi08Handshake(io.undertow.websockets.core.protocol.version08.Hybi08Handshake)

Example 14 with WebSocketChannel

use of io.undertow.websockets.core.WebSocketChannel 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)

Example 15 with WebSocketChannel

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

the class JsrHybi08Handshake method createChannel.

@Override
public WebSocketChannel createChannel(WebSocketHttpExchange exchange, final StreamConnection c, final ByteBufferPool buffers) {
    WebSocketChannel channel = super.createChannel(exchange, c, buffers);
    HandshakeUtil.setConfig(channel, config);
    return channel;
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel)

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