Search in sources :

Example 6 with AbstractReceiveListener

use of io.undertow.websockets.core.AbstractReceiveListener 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) {
            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) {
            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(10, TimeUnit.SECONDS);
        assertEquals(message, res);
    }
    clientChannel.sendClose();
}
Also used : WebSocketExtension(io.undertow.websockets.WebSocketExtension) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) 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 7 with AbstractReceiveListener

use of io.undertow.websockets.core.AbstractReceiveListener 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 8 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) {
    // 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 9 with AbstractReceiveListener

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

the class WebSocketClient13TestCase method testTextMessage.

@Test
public void testTextMessage() throws Exception {
    final WebSocketChannel webSocketChannel = WebSocketClient.connectionBuilder(worker, DefaultServer.getBufferPool(), new URI(DefaultServer.getDefaultServerURL())).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();
}
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) Test(org.junit.Test)

Example 10 with AbstractReceiveListener

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

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