Search in sources :

Example 1 with SendResult

use of javax.websocket.SendResult in project tomcat by apache.

the class WsSession method doClose.

/**
     * WebSocket 1.0. Section 2.1.5.
     * Need internal close method as spec requires that the local endpoint
     * receives a 1006 on timeout.
     *
     * @param closeReasonMessage The close reason to pass to the remote endpoint
     * @param closeReasonLocal   The close reason to pass to the local endpoint
     */
public void doClose(CloseReason closeReasonMessage, CloseReason closeReasonLocal) {
    // Double-checked locking. OK because state is volatile
    if (state != State.OPEN) {
        return;
    }
    synchronized (stateLock) {
        if (state != State.OPEN) {
            return;
        }
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("wsSession.doClose", id));
        }
        try {
            wsRemoteEndpoint.setBatchingAllowed(false);
        } catch (IOException e) {
            log.warn(sm.getString("wsSession.flushFailOnClose"), e);
            fireEndpointOnError(e);
        }
        state = State.OUTPUT_CLOSED;
        sendCloseMessage(closeReasonMessage);
        fireEndpointOnClose(closeReasonLocal);
    }
    IOException ioe = new IOException(sm.getString("wsSession.messageFailed"));
    SendResult sr = new SendResult(ioe);
    for (FutureToSendHandler f2sh : futures.keySet()) {
        f2sh.onResult(sr);
    }
}
Also used : SendResult(javax.websocket.SendResult) IOException(java.io.IOException)

Example 2 with SendResult

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

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

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

the class SendHandlerAdapter method complete.

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

Example 5 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)

Aggregations

SendResult (javax.websocket.SendResult)13 IOException (java.io.IOException)6 SendHandler (javax.websocket.SendHandler)5 URI (java.net.URI)4 ByteBuffer (java.nio.ByteBuffer)4 Session (javax.websocket.Session)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)2 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 OutputStream (java.io.OutputStream)2 Writer (java.io.Writer)2 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)2 EncodeException (javax.websocket.EncodeException)2 Encoder (javax.websocket.Encoder)2 Extension (javax.websocket.Extension)2 DeflateFrameExtension (org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension)2