Search in sources :

Example 11 with SendResult

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

the class JsrAsyncRemote method sendObject.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void sendObject(Object data, SendHandler handler) {
    assertMessageNotNull(data);
    assertSendHandlerNotNull(handler);
    if (LOG.isDebugEnabled()) {
        LOG.debug("sendObject({},{})", data, handler);
    }
    Encoder encoder = encoders.getEncoderFor(data.getClass());
    if (encoder == null) {
        throw new IllegalArgumentException("No encoder for type: " + data.getClass());
    }
    if (encoder instanceof Encoder.Text) {
        Encoder.Text etxt = (Encoder.Text) encoder;
        try {
            String msg = etxt.encode(data);
            sendText(msg, handler);
            return;
        } catch (EncodeException e) {
            handler.onResult(new SendResult(e));
        }
    } else if (encoder instanceof Encoder.TextStream) {
        Encoder.TextStream etxt = (Encoder.TextStream) encoder;
        SendHandlerWriteCallback callback = new SendHandlerWriteCallback(handler);
        try (MessageWriter writer = new MessageWriter(session)) {
            writer.setCallback(callback);
            etxt.encode(data, writer);
            return;
        } catch (EncodeException | IOException e) {
            handler.onResult(new SendResult(e));
        }
    } else if (encoder instanceof Encoder.Binary) {
        Encoder.Binary ebin = (Encoder.Binary) encoder;
        try {
            ByteBuffer buf = ebin.encode(data);
            sendBinary(buf, handler);
            return;
        } catch (EncodeException e) {
            handler.onResult(new SendResult(e));
        }
    } else if (encoder instanceof Encoder.BinaryStream) {
        Encoder.BinaryStream ebin = (Encoder.BinaryStream) encoder;
        SendHandlerWriteCallback callback = new SendHandlerWriteCallback(handler);
        try (MessageOutputStream out = new MessageOutputStream(session)) {
            out.setCallback(callback);
            ebin.encode(data, out);
            return;
        } catch (EncodeException | IOException e) {
            handler.onResult(new SendResult(e));
        }
    }
    throw new IllegalArgumentException("Unknown encoder type: " + encoder);
}
Also used : EncodeException(javax.websocket.EncodeException) ByteBuffer(java.nio.ByteBuffer) SendHandlerWriteCallback(org.eclipse.jetty.websocket.jsr356.messages.SendHandlerWriteCallback) MessageOutputStream(org.eclipse.jetty.websocket.common.message.MessageOutputStream) Encoder(javax.websocket.Encoder) SendResult(javax.websocket.SendResult) MessageWriter(org.eclipse.jetty.websocket.common.message.MessageWriter)

Example 12 with SendResult

use of javax.websocket.SendResult 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 13 with SendResult

use of javax.websocket.SendResult 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 14 with SendResult

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

the class JsrWebSocketServer07Test method testTextByCompletion.

@org.junit.Test
public void testTextByCompletion() 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 latch2 = new FutureResult();
    class TestEndPoint extends Endpoint {

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

                @Override
                public void onMessage(String message) {
                    session.getAsyncRemote().sendText(message, 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.getWorker(), DefaultServer.getBufferPool(), Collections.EMPTY_LIST, 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 TextWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    latch2.getIoFuture().get();
    SendResult result = sendResult.get();
    Assert.assertNotNull(result);
    Assert.assertNull(result.getException());
    client.destroy();
}
Also used : SendHandler(javax.websocket.SendHandler) MessageHandler(javax.websocket.MessageHandler) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) 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) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) FrameChecker(io.undertow.websockets.utils.FrameChecker) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession) Test(org.junit.Test)

Example 15 with SendResult

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

the class SendHandlerAdapter method onError.

@Override
public void onError(WebSocketChannel channel, Void context, Throwable throwable) {
    if (done) {
        return;
    }
    done = true;
    handler.onResult(new SendResult(throwable));
}
Also used : SendResult(javax.websocket.SendResult)

Aggregations

SendResult (javax.websocket.SendResult)16 IOException (java.io.IOException)7 SendHandler (javax.websocket.SendHandler)7 ByteBuffer (java.nio.ByteBuffer)5 URI (java.net.URI)4 Session (javax.websocket.Session)4 Test (org.junit.Test)4 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)2 UndertowSession (io.undertow.websockets.jsr.UndertowSession)2 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)2 FrameChecker (io.undertow.websockets.utils.FrameChecker)2 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)2 SocketTimeoutException (java.net.SocketTimeoutException)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)2 EncodeException (javax.websocket.EncodeException)2 Encoder (javax.websocket.Encoder)2 Endpoint (javax.websocket.Endpoint)2