Search in sources :

Example 1 with AbstractReceiveListener

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

the class WebSocketClient13TestCase method testTextMessageWss.

@Test
public void testTextMessageWss() throws Exception {
    UndertowXnioSsl ssl = new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, DefaultServer.getClientSSLContext());
    final WebSocketClient.ConnectionBuilder connectionBuilder = WebSocketClient.connectionBuilder(worker, DefaultServer.getBufferPool(), new URI("wss://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostSSLPort("default"))).setSsl(ssl);
    IoFuture<WebSocketChannel> future = connectionBuilder.connect();
    future.await(4, TimeUnit.SECONDS);
    final WebSocketChannel webSocketChannel = future.get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    webSocketChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
            String data = message.getData();
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    webSocketChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = webSocketChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello World").setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("Hello World", result.get());
    webSocketChannel.sendClose();
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) WebSocketClient(io.undertow.websockets.client.WebSocketClient) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) Test(org.junit.Test)

Example 2 with AbstractReceiveListener

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

use of io.undertow.websockets.core.AbstractReceiveListener 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();
    stopWorker(client);
    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 4 with AbstractReceiveListener

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

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

the class WebSocketClient13TestCase method testMessageViaWssProxy.

@Test
@ProxyIgnore
public void testMessageViaWssProxy() throws Exception {
    final WebSocketChannel webSocketChannel = WebSocketClient.connectionBuilder(worker, DefaultServer.getBufferPool(), new URI(DefaultServer.getDefaultServerSSLAddress())).setSsl(new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, DefaultServer.getClientSSLContext())).setProxyUri(new URI("http", null, DefaultServer.getHostAddress("default"), DefaultServer.getHostPort("default") + 10, "/proxy", null, null)).connect().get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    webSocketChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
            String data = message.getData();
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    webSocketChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = webSocketChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello World").setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("Hello World", result.get());
    webSocketChannel.sendClose();
    Assert.assertEquals("CONNECT " + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostSSLPort("default"), connectLog.poll());
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) Test(org.junit.Test) ProxyIgnore(io.undertow.testutils.ProxyIgnore)

Aggregations

AbstractReceiveListener (io.undertow.websockets.core.AbstractReceiveListener)21 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)21 BufferedTextMessage (io.undertow.websockets.core.BufferedTextMessage)18 URI (java.net.URI)16 Test (org.junit.Test)15 IOException (java.io.IOException)14 CountDownLatch (java.util.concurrent.CountDownLatch)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 WebSocketConnectionCallback (io.undertow.websockets.WebSocketConnectionCallback)9 BufferedBinaryMessage (io.undertow.websockets.core.BufferedBinaryMessage)9 WebSocketHttpExchange (io.undertow.websockets.spi.WebSocketHttpExchange)9 StringWriteChannelListener (io.undertow.util.StringWriteChannelListener)8 WebSocketProtocolHandshakeHandler (io.undertow.websockets.WebSocketProtocolHandshakeHandler)8 StreamSinkFrameChannel (io.undertow.websockets.core.StreamSinkFrameChannel)8 WebSocketClientNegotiation (io.undertow.websockets.client.WebSocketClientNegotiation)5 FrameChecker (io.undertow.websockets.utils.FrameChecker)5 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 FutureResult (org.xnio.FutureResult)5 WebSocketExtension (io.undertow.websockets.WebSocketExtension)4