Search in sources :

Example 16 with BufferedTextMessage

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

the class WebSocketExtensionBasicTestCase method testLongTextMessage.

@Test
public void testLongTextMessage() 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<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(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.");
            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();
    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));
    }
    WebSockets.sendTextBlocking(longMsg.toString(), clientChannel);
    latch.await(300, TimeUnit.SECONDS);
    Assert.assertEquals(longMsg.toString(), result.get());
    clientChannel.sendClose();
    stopWorker(client);
}
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) HashSet(java.util.HashSet) WebSocketExtension(io.undertow.websockets.WebSocketExtension) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 17 with BufferedTextMessage

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

the class ChatServer method main.

public static void main(final String[] args) {
    System.out.println("To see chat in action is to open two different browsers and point them at http://localhost:8080");
    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) {
                    final String messageData = message.getData();
                    for (WebSocketChannel session : channel.getPeerConnections()) {
                        WebSockets.sendText(messageData, session, null);
                    }
                }
            });
            channel.resumeReceives();
        }
    })).addPrefixPath("/", resource(new ClassPathResourceManager(ChatServer.class.getClassLoader(), ChatServer.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 18 with BufferedTextMessage

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

the class FrameHandler method onText.

@Override
protected void onText(WebSocketChannel webSocketChannel, StreamSourceFrameChannel messageChannel) throws IOException {
    if (session.isSessionClosed()) {
        // to bad, the channel has already been closed
        // we just ignore messages that are received after we have closed, as the endpoint is no longer in a valid state to deal with them
        // this this should only happen if a message was on the wire when we called close()
        messageChannel.close();
        return;
    }
    final HandlerWrapper handler = getHandler(FrameType.TEXT);
    if (handler != null && handler.isPartialHandler()) {
        BufferedTextMessage data = new BufferedTextMessage(false);
        data.read(messageChannel, new WebSocketCallback<BufferedTextMessage>() {

            @Override
            public void complete(WebSocketChannel channel, BufferedTextMessage context) {
                invokeTextHandler(context, handler, context.isComplete());
            }

            @Override
            public void onError(WebSocketChannel channel, BufferedTextMessage context, Throwable throwable) {
                invokeOnError(throwable);
            }
        });
    } else {
        bufferFullMessage(messageChannel);
    }
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage)

Example 19 with BufferedTextMessage

use of io.undertow.websockets.core.BufferedTextMessage in project actframework by actframework.

the class UndertowWebSocketConnectionHandler method handle.

@Override
public void handle(final ActionContext context) {
    if (logger.isTraceEnabled()) {
        logger.trace("handle websocket connection request to %s", context.req().url());
    }
    final UndertowRequest req = (UndertowRequest) context.req();
    HttpServerExchange exchange = req.exchange();
    try {
        Handlers.websocket(new WebSocketConnectionCallback() {

            @Override
            public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
                final WebSocketConnection connection = new UndertowWebSocketConnection(channel, context.session());
                channel.setAttribute("act_conn", connection);
                connectionManager.registerNewConnection(connection, context);
                final WebSocketContext wsCtx = new WebSocketContext(req.url(), connection, connectionManager, context, connectionManager.app());
                if (logger.isTraceEnabled()) {
                    logger.trace("websocket context[%s] created for %s", connection.sessionId(), context.req().url());
                }
                channel.getReceiveSetter().set(new AbstractReceiveListener() {

                    @Override
                    protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
                        WebSocketContext.current(wsCtx);
                        String payload = message.getData();
                        if (logger.isTraceEnabled()) {
                            logger.trace("websocket message received: %s", payload);
                        }
                        wsCtx.messageReceived(payload);
                        invoke(wsCtx);
                    }

                    @Override
                    protected void onClose(WebSocketChannel webSocketChannel, StreamSourceFrameChannel channel) throws IOException {
                        if (logger.isTraceEnabled()) {
                            logger.trace("websocket closed: ", connection.sessionId());
                        }
                        WebSocketContext.current(wsCtx);
                        super.onClose(webSocketChannel, channel);
                        connection.destroy();
                        context.app().eventBus().emit(new WebSocketCloseEvent(wsCtx));
                    }
                });
                channel.resumeReceives();
                Act.eventBus().emit(new WebSocketConnectEvent(wsCtx));
            }
        }).handleRequest(exchange);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw ActErrorResult.of(e);
    }
}
Also used : WebSocketCloseEvent(act.ws.WebSocketCloseEvent) WebSocketConnectEvent(act.ws.WebSocketConnectEvent) WebSocketConnection(act.xio.WebSocketConnection) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) IOException(java.io.IOException) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) IOException(java.io.IOException) WebSocketContext(act.ws.WebSocketContext) HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) StreamSourceFrameChannel(io.undertow.websockets.core.StreamSourceFrameChannel) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback)

Aggregations

BufferedTextMessage (io.undertow.websockets.core.BufferedTextMessage)19 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)19 AbstractReceiveListener (io.undertow.websockets.core.AbstractReceiveListener)18 URI (java.net.URI)13 Test (org.junit.Test)12 IOException (java.io.IOException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 StringWriteChannelListener (io.undertow.util.StringWriteChannelListener)8 StreamSinkFrameChannel (io.undertow.websockets.core.StreamSinkFrameChannel)8 WebSocketConnectionCallback (io.undertow.websockets.WebSocketConnectionCallback)6 BufferedBinaryMessage (io.undertow.websockets.core.BufferedBinaryMessage)6 WebSocketHttpExchange (io.undertow.websockets.spi.WebSocketHttpExchange)6 WebSocketProtocolHandshakeHandler (io.undertow.websockets.WebSocketProtocolHandshakeHandler)5 WebSocketClientNegotiation (io.undertow.websockets.client.WebSocketClientNegotiation)5 WebSocketExtension (io.undertow.websockets.WebSocketExtension)4 HashSet (java.util.HashSet)4 Undertow (io.undertow.Undertow)3 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)3 ClassPathResourceManager (io.undertow.server.handlers.resource.ClassPathResourceManager)3