Search in sources :

Example 21 with CloseReason

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

the class WsRemoteEndpointImplBase method sendMessageBlock.

private void sendMessageBlock(byte opCode, ByteBuffer payload, boolean last, long timeoutExpiry) throws IOException {
    wsSession.updateLastActive();
    BlockingSendHandler bsh = new BlockingSendHandler();
    List<MessagePart> messageParts = new ArrayList<>();
    messageParts.add(new MessagePart(last, 0, opCode, payload, bsh, bsh, timeoutExpiry));
    messageParts = transformation.sendMessagePart(messageParts);
    // return.
    if (messageParts.size() == 0) {
        return;
    }
    long timeout = timeoutExpiry - System.currentTimeMillis();
    try {
        if (!messagePartInProgress.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
            String msg = sm.getString("wsRemoteEndpoint.acquireTimeout");
            wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, msg), new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg));
            throw new SocketTimeoutException(msg);
        }
    } catch (InterruptedException e) {
        String msg = sm.getString("wsRemoteEndpoint.sendInterrupt");
        wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, msg), new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg));
        throw new IOException(msg, e);
    }
    for (MessagePart mp : messageParts) {
        writeMessagePart(mp);
        if (!bsh.getSendResult().isOK()) {
            messagePartInProgress.release();
            Throwable t = bsh.getSendResult().getException();
            wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, t.getMessage()), new CloseReason(CloseCodes.CLOSED_ABNORMALLY, t.getMessage()));
            throw new IOException(t);
        }
        // The BlockingSendHandler doesn't call end message so update the
        // flags.
        fragmented = nextFragmented;
        text = nextText;
    }
    if (payload != null) {
        payload.clear();
    }
    endMessage(null, null);
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) CloseReason(javax.websocket.CloseReason) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Example 22 with CloseReason

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

the class OnCloseCallable method call.

public void call(Object endpoint, int statusCode, String reason) {
    // Close Reason is an optional parameter
    if (idxCloseReason >= 0) {
        // convert to javax.websocket.CloseReason
        CloseReason jsrclose = new CloseReason(CloseCodes.getCloseCode(statusCode), reason);
        super.args[idxCloseReason] = jsrclose;
    }
    super.call(endpoint, super.args);
}
Also used : CloseReason(javax.websocket.CloseReason)

Example 23 with CloseReason

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

the class JsrWebSocketServer07Test method testCloseFrameWithoutReasonBody.

/**
     * Section 5.5.1 of RFC 6455 says the reason body is optional
     */
@org.junit.Test
public void testCloseFrameWithoutReasonBody() throws Exception {
    final int code = 1000;
    final AtomicReference<CloseReason> reason = new AtomicReference<>();
    ByteBuffer payload = ByteBuffer.allocate(2);
    payload.putShort((short) code);
    payload.flip();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();
    final CountDownLatch clientLatch = new CountDownLatch(1);
    final AtomicInteger closeCount = new AtomicInteger();
    class TestEndPoint extends Endpoint {

        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
        }

        @Override
        public void onClose(Session session, CloseReason closeReason) {
            closeCount.incrementAndGet();
            reason.set(closeReason);
            clientLatch.countDown();
        }
    }
    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 CloseWebSocketFrame(code, null), new FrameChecker(CloseWebSocketFrame.class, payload.array(), latch));
    if (latch.getIoFuture().await(10, TimeUnit.SECONDS) != IoFuture.Status.DONE) {
        Assert.fail();
    }
    latch.getIoFuture().get();
    clientLatch.await();
    Assert.assertEquals(code, reason.get().getCloseCode().getCode());
    Assert.assertEquals("", reason.get().getReasonPhrase());
    Assert.assertEquals(1, closeCount.get());
    client.destroy();
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) 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) CloseReason(javax.websocket.CloseReason) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) 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 24 with CloseReason

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

the class WebsocketStressTestCase method websocketFragmentationStressTestCase.

@Test
public void websocketFragmentationStressTestCase() throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final CountDownLatch done = new CountDownLatch(1);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; ++i) {
        sb.append("message ");
        sb.append(i);
    }
    String toSend = sb.toString();
    final Session session = defaultContainer.connectToServer(new Endpoint() {

        @Override
        public void onOpen(Session session, EndpointConfig config) {
            session.addMessageHandler(new MessageHandler.Partial<byte[]>() {

                @Override
                public void onMessage(byte[] bytes, boolean b) {
                    try {
                        out.write(bytes);
                    } catch (IOException e) {
                        e.printStackTrace();
                        done.countDown();
                    }
                    if (b) {
                        done.countDown();
                    }
                }
            });
        }

        @Override
        public void onClose(Session session, CloseReason closeReason) {
            done.countDown();
        }

        @Override
        public void onError(Session session, Throwable thr) {
            thr.printStackTrace();
            done.countDown();
        }
    }, null, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/stress"));
    OutputStream stream = session.getBasicRemote().getSendStream();
    for (int i = 0; i < toSend.length(); ++i) {
        stream.write(toSend.charAt(i));
        stream.flush();
    }
    stream.close();
    done.await(40, TimeUnit.SECONDS);
    Assert.assertEquals(toSend, new String(out.toByteArray()));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) Endpoint(javax.websocket.Endpoint) CloseReason(javax.websocket.CloseReason) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) Test(org.junit.Test)

Example 25 with CloseReason

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

the class WebsocketStressTestCase method webSocketStringStressTestCase.

@Test
public void webSocketStringStressTestCase() throws Exception {
    List<CountDownLatch> latches = new ArrayList<>();
    for (int i = 0; i < NUM_THREADS; ++i) {
        final CountDownLatch latch = new CountDownLatch(1);
        latches.add(latch);
        final Session session = deployment.connectToServer(new Endpoint() {

            @Override
            public void onOpen(Session session, EndpointConfig config) {
            }

            @Override
            public void onClose(Session session, CloseReason closeReason) {
                latch.countDown();
            }

            @Override
            public void onError(Session session, Throwable thr) {
                latch.countDown();
            }
        }, null, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/stress"));
        final int thread = i;
        executor.submit(new Runnable() {

            @Override
            public void run() {
                try {
                    executor.submit(new SendRunnable(session, thread, executor));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
    for (CountDownLatch future : latches) {
        future.await();
    }
    for (int t = 0; t < NUM_THREADS; ++t) {
        for (int i = 0; i < NUM_REQUESTS; ++i) {
            String msg = "t-" + t + "-m-" + i;
            Assert.assertTrue(msg, StressEndpoint.MESSAGES.remove(msg));
        }
    }
    Assert.assertEquals(0, StressEndpoint.MESSAGES.size());
}
Also used : ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) IOException(java.io.IOException) Endpoint(javax.websocket.Endpoint) CloseReason(javax.websocket.CloseReason) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) Test(org.junit.Test)

Aggregations

CloseReason (javax.websocket.CloseReason)29 IOException (java.io.IOException)16 Session (javax.websocket.Session)8 URI (java.net.URI)7 Test (org.junit.Test)6 ByteBuffer (java.nio.ByteBuffer)5 Endpoint (javax.websocket.Endpoint)5 CountDownLatch (java.util.concurrent.CountDownLatch)4 EndpointConfig (javax.websocket.EndpointConfig)4 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)3 UndertowSession (io.undertow.websockets.jsr.UndertowSession)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)2 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)2 FrameChecker (io.undertow.websockets.utils.FrameChecker)2 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)2 CoderResult (java.nio.charset.CoderResult)2 ArrayList (java.util.ArrayList)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2