Search in sources :

Example 1 with SendHandler

use of javax.websocket.SendHandler in project tomcat70 by apache.

the class WsRemoteEndpointImplServer method clearHandler.

/**
 * @param t             The throwable associated with any error that
 *                      occurred
 * @param useDispatch   Should {@link SendHandler#onResult(SendResult)} be
 *                      called from a new thread, keeping in mind the
 *                      requirements of
 *                      {@link javax.websocket.RemoteEndpoint.Async}
 */
private void clearHandler(Throwable t, boolean useDispatch) {
    // Setting the result marks this (partial) message as
    // complete which means the next one may be sent which
    // could update the value of the handler. Therefore, keep a
    // local copy before signalling the end of the (partial)
    // message.
    SendHandler sh = handler;
    handler = null;
    buffers = null;
    if (sh != null) {
        if (useDispatch) {
            OnResultRunnable r = onResultRunnables.poll();
            if (r == null) {
                r = new OnResultRunnable(onResultRunnables);
            }
            r.init(sh, t);
            if (executorService == null || executorService.isShutdown()) {
                // Can't use the executor so call the runnable directly.
                // This may not be strictly specification compliant in all
                // cases but during shutdown only close messages are going
                // to be sent so there should not be the issue of nested
                // calls leading to stack overflow as described in bug
                // 55715. The issues with nested calls was the reason for
                // the separate thread requirement in the specification.
                r.run();
            } else {
                executorService.execute(r);
            }
        } else {
            if (t == null) {
                sh.onResult(new SendResult());
            } else {
                sh.onResult(new SendResult(t));
            }
        }
    }
}
Also used : SendHandler(javax.websocket.SendHandler) SendResult(javax.websocket.SendResult)

Example 2 with SendHandler

use of javax.websocket.SendHandler in project undertow by undertow-io.

the class JsrWebSocketServer07Test method testBinaryWithByteBufferByCompletion.

@org.junit.Test
public void testBinaryWithByteBufferByCompletion() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<SendResult> sendResult = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult<?> latch = new FutureResult<>();
    final FutureResult<Void> latch2 = new FutureResult<>();
    class TestEndPoint extends Endpoint {

        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
            session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {

                @Override
                public void onMessage(ByteBuffer message) {
                    ByteBuffer buf = ByteBuffer.allocate(message.remaining());
                    buf.put(message);
                    buf.flip();
                    session.getAsyncRemote().sendBinary(buf, new SendHandler() {

                        @Override
                        public void onResult(SendResult result) {
                            sendResult.set(result);
                            if (result.getException() != null) {
                                latch2.setException(new IOException(result.getException()));
                            } else {
                                latch2.setResult(null);
                            }
                        }
                    });
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorkerSupplier(), DefaultServer.getBufferPool(), Collections.emptyList(), false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    // FIXME UNDERTOW-1862 assertEquals(DONE, latch.getIoFuture().await());
    latch.getIoFuture().await();
    assertEquals(DONE, latch2.getIoFuture().await());
    SendResult result = sendResult.get();
    Assert.assertNotNull(result);
    assertNull(result.getException());
    client.destroy();
}
Also used : SendHandler(javax.websocket.SendHandler) MessageHandler(javax.websocket.MessageHandler) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) URI(java.net.URI) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) SendResult(javax.websocket.SendResult) FrameChecker(io.undertow.websockets.utils.FrameChecker) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession)

Example 3 with SendHandler

use of javax.websocket.SendHandler in project jetty.project by eclipse.

the class ExtensionStackProcessingTest method testDeflateFrameExtension.

@Test
public void testDeflateFrameExtension() throws Exception {
    assumeDeflateFrameAvailable();
    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().extensions(Arrays.<Extension>asList(new JsrExtension("deflate-frame"))).build();
    final String content = "deflate_me";
    final CountDownLatch messageLatch = new CountDownLatch(1);
    URI uri = URI.create("ws://localhost:" + connector.getLocalPort());
    Session session = client.connectToServer(new EndpointAdapter() {

        @Override
        public void onMessage(String message) {
            Assert.assertEquals(content, message);
            messageLatch.countDown();
        }
    }, config, uri);
    // Make sure everything is wired properly.
    OutgoingFrames firstOut = ((JsrSession) session).getOutgoingHandler();
    Assert.assertTrue(firstOut instanceof ExtensionStack);
    ExtensionStack extensionStack = (ExtensionStack) firstOut;
    Assert.assertTrue(extensionStack.isRunning());
    OutgoingFrames secondOut = extensionStack.getNextOutgoing();
    Assert.assertTrue(secondOut instanceof DeflateFrameExtension);
    DeflateFrameExtension deflateExtension = (DeflateFrameExtension) secondOut;
    Assert.assertTrue(deflateExtension.isRunning());
    OutgoingFrames thirdOut = deflateExtension.getNextOutgoing();
    Assert.assertTrue(thirdOut instanceof WebSocketClientConnection);
    final CountDownLatch latch = new CountDownLatch(1);
    session.getAsyncRemote().sendText(content, new SendHandler() {

        @Override
        public void onResult(SendResult result) {
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(messageLatch.await(5, TimeUnit.SECONDS));
}
Also used : SendHandler(javax.websocket.SendHandler) WebSocketClientConnection(org.eclipse.jetty.websocket.client.io.WebSocketClientConnection) JsrSession(org.eclipse.jetty.websocket.jsr356.JsrSession) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ExtensionStack(org.eclipse.jetty.websocket.common.extensions.ExtensionStack) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) Extension(javax.websocket.Extension) DeflateFrameExtension(org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) SendResult(javax.websocket.SendResult) OutgoingFrames(org.eclipse.jetty.websocket.api.extensions.OutgoingFrames) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) DeflateFrameExtension(org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension) Session(javax.websocket.Session) JsrSession(org.eclipse.jetty.websocket.jsr356.JsrSession) Test(org.junit.Test)

Example 4 with SendHandler

use of javax.websocket.SendHandler in project jetty.project by eclipse.

the class ExtensionStackProcessingTest method testPerMessageDeflateExtension.

@Test
public void testPerMessageDeflateExtension() throws Exception {
    assumeDeflateFrameAvailable();
    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().extensions(Arrays.<Extension>asList(new JsrExtension("permessage-deflate"))).build();
    final String content = "deflate_me";
    final CountDownLatch messageLatch = new CountDownLatch(1);
    URI uri = URI.create("ws://localhost:" + connector.getLocalPort());
    Session session = client.connectToServer(new EndpointAdapter() {

        @Override
        public void onMessage(String message) {
            Assert.assertEquals(content, message);
            messageLatch.countDown();
        }
    }, config, uri);
    final CountDownLatch latch = new CountDownLatch(1);
    session.getAsyncRemote().sendText(content, new SendHandler() {

        @Override
        public void onResult(SendResult result) {
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(messageLatch.await(5, TimeUnit.SECONDS));
}
Also used : Extension(javax.websocket.Extension) DeflateFrameExtension(org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) SendHandler(javax.websocket.SendHandler) SendResult(javax.websocket.SendResult) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) Session(javax.websocket.Session) JsrSession(org.eclipse.jetty.websocket.jsr356.JsrSession) Test(org.junit.Test)

Example 5 with SendHandler

use of javax.websocket.SendHandler in project tomcat70 by apache.

the class WsRemoteEndpointImplBase method writeMessagePart.

void writeMessagePart(MessagePart mp) {
    if (closed) {
        throw new IllegalStateException(sm.getString("wsRemoteEndpoint.closed"));
    }
    if (Constants.INTERNAL_OPCODE_FLUSH == mp.getOpCode()) {
        nextFragmented = fragmented;
        nextText = text;
        outputBuffer.flip();
        SendHandler flushHandler = new OutputBufferFlushSendHandler(outputBuffer, mp.getEndHandler());
        doWrite(flushHandler, outputBuffer);
        return;
    }
    // Control messages may be sent in the middle of fragmented message
    // so they have no effect on the fragmented or text flags
    boolean first;
    if (Util.isControl(mp.getOpCode())) {
        nextFragmented = fragmented;
        nextText = text;
        if (mp.getOpCode() == Constants.OPCODE_CLOSE) {
            closed = true;
        }
        first = true;
    } else {
        boolean isText = Util.isText(mp.getOpCode());
        if (fragmented) {
            // Currently fragmented
            if (text != isText) {
                throw new IllegalStateException(sm.getString("wsRemoteEndpoint.changeType"));
            }
            nextText = text;
            nextFragmented = !mp.isFin();
            first = false;
        } else {
            // Wasn't fragmented. Might be now
            if (mp.isFin()) {
                nextFragmented = false;
            } else {
                nextFragmented = true;
                nextText = isText;
            }
            first = true;
        }
    }
    byte[] mask;
    if (isMasked()) {
        mask = Util.generateMask();
    } else {
        mask = null;
    }
    headerBuffer.clear();
    writeHeader(headerBuffer, mp.isFin(), mp.getRsv(), mp.getOpCode(), isMasked(), mp.getPayload(), mask, first);
    headerBuffer.flip();
    if (getBatchingAllowed() || isMasked()) {
        // Need to write via output buffer
        OutputBufferSendHandler obsh = new OutputBufferSendHandler(mp.getEndHandler(), headerBuffer, mp.getPayload(), mask, outputBuffer, !getBatchingAllowed(), this);
        obsh.write();
    } else {
        // Can write directly
        doWrite(mp.getEndHandler(), headerBuffer, mp.getPayload());
    }
}
Also used : SendHandler(javax.websocket.SendHandler)

Aggregations

SendHandler (javax.websocket.SendHandler)5 SendResult (javax.websocket.SendResult)4 URI (java.net.URI)3 Session (javax.websocket.Session)3 CountDownLatch (java.util.concurrent.CountDownLatch)2 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)2 Extension (javax.websocket.Extension)2 DeflateFrameExtension (org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension)2 JsrExtension (org.eclipse.jetty.websocket.jsr356.JsrExtension)2 JsrSession (org.eclipse.jetty.websocket.jsr356.JsrSession)2 Test (org.junit.Test)2 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)1 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)1 UndertowSession (io.undertow.websockets.jsr.UndertowSession)1 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)1 FrameChecker (io.undertow.websockets.utils.FrameChecker)1 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)1 IOException (java.io.IOException)1 ByteBuffer (java.nio.ByteBuffer)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1