Java Code Examples for javax.websocket.Session#close()

The following examples show how to use javax.websocket.Session#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotatedEndpointTest.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseReason() throws Exception {
    AnnotatedClientEndpoint.reset();
    MessageEndpoint.reset();

    Session session = deployment.connectToServer(AnnotatedClientEndpoint.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/chat/Bob"));

    Assert.assertEquals("hi Bob (protocol=foo)", AnnotatedClientEndpoint.message());

    session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Foo!"));
    Assert.assertEquals("CLOSED", AnnotatedClientEndpoint.message());
    CloseReason cr = MessageEndpoint.getReason();
    Assert.assertEquals(CloseReason.CloseCodes.VIOLATED_POLICY.getCode(), cr.getCloseCode().getCode());
    Assert.assertEquals("Foo!", cr.getReasonPhrase());

}
 
Example 2
Source File: SynchronizeFXWebsocketChannel.java    From SynchronizeFX with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void shutdown() {
    synchronized (connections) {
        parent.channelCloses(this);
        for (final Session connection : connections) {
            final ExecutorService executorService = connectionThreads.get(connection);
            try {
                // If there is no executor service for a client, it may has already been shut down.
                if (executorService != null) {
                    executorService.shutdownNow();
                }
                connection
                        .close(new CloseReason(CloseCodes.GOING_AWAY, "This SynchronizeFX channel is closed now."));
            } catch (final IOException e) {
                callback.onClientConnectionError(connection,
                        new SynchronizeFXException("Failed to close the connection to a connected client.", e));
            } finally {
                connectionThreads.remove(connection);
            }
        }
        connections.clear();
    }
    callback = null;
}
 
Example 3
Source File: TesterEchoServer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@OnMessage
public void echoTextMessage(Session session, @SuppressWarnings("unused") String msg) {
    try {
        session.getBasicRemote().sendText(msg);
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 4
Source File: PushSocket.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean validate(Session session, String ticket, Integer owner) throws IOException{
    if (! ticketingServices.validateTicket(ticket, owner)){
        logger.info("Invalid ticket for session " + session );
        session.close( new CloseReason( CloseCodes.CANNOT_ACCEPT, "Invalid ticket"));
        return false;
    } else {
        return true;
    }
}
 
Example 5
Source File: AnnotatedEndpointConnectionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void closeConnection() throws Exception {
	try {
		Session session = this.session;
		if (session != null && session.isOpen()) {
			session.close();
		}
	}
	finally {
		this.session = null;
	}
}
 
Example 6
Source File: TesterWsClientAutobahn.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
    try {
        if (session.isOpen()) {
            session.getBasicRemote().sendText(msg, last);
        }
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 7
Source File: EndpointConnectionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void closeConnection() throws Exception {
	try {
		Session session = this.session;
		if (session != null && session.isOpen()) {
			session.close();
		}
	}
	finally {
		this.session = null;
	}
}
 
Example 8
Source File: TesterWsClientAutobahn.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@OnMessage
public void echoBinaryMessage(Session session, ByteBuffer bb,
        boolean last) {
    try {
        if (session.isOpen()) {
            session.getBasicRemote().sendBinary(bb, last);
        }
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 9
Source File: TesterEchoServer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@OnMessage(maxMessageSize = MAX_SIZE)
public void echoBinaryMessage(Session session, ByteBuffer msg) {
    try {
        session.getBasicRemote().sendBinary(msg);
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 10
Source File: TesterEchoServer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@OnMessage
public void echoTextMessage(Session session, @SuppressWarnings("unused") String msg) {
    try {
        session.getBasicRemote().getSendWriter();
        // Simulate an error
        throw new RuntimeException();
    } catch (IOException e) {
        // Should not happen
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 11
Source File: PojoEndpointBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void handleOnOpenError(Session session, Throwable t) {
    // If really fatal - re-throw
    ExceptionUtils.handleThrowable(t);

    // Trigger the error handler and close the session
    onError(session, t);
    try {
        session.close();
    } catch (IOException ioe) {
        log.warn(sm.getString("pojoEndpointBase.closeSessionFail"), ioe);
    }
}
 
Example 12
Source File: CmdWebSocket.java    From spring-boot-101 with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen(Session session) throws IOException{
	this.session = session;
	webSocketSet.add(this);
	if(getOnlineCount()>0){
		this.sendMessage("对不起,此服务只允许有一个连接。请稍后再试。");
		session.close();
		return;
	}

	incrOnlineCount();

	logger.info("new connection...current online count: {}", getOnlineCount());
}
 
Example 13
Source File: TesterEchoServer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@OnMessage(maxMessageSize = MAX_SIZE)
public void echoTextMessage(Session session, String msg) {
    try {
        session.getBasicRemote().sendText(msg);
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 14
Source File: CodingClient.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static void close() {
    for (Session session : sessions) {
        try {
            session.close();
        } catch (IOException ignored) {
        }
    }

}
 
Example 15
Source File: TesterEchoServer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@OnMessage
public void echoBinaryMessage(Session session, ByteBuffer msg,
        boolean last) {
    try {
        session.getBasicRemote().sendBinary(msg, last);
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 16
Source File: EchoAnnotation.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
    try {
        if (session.isOpen()) {
            session.getBasicRemote().sendText(msg, last);
        }
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 17
Source File: TestWebSocketFrameClientSSL.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug56032() throws Exception {
    // TODO Investigate options to get this test to pass with the HTTP BIO
    //      connector.
    Assume.assumeFalse(
            "Skip this test on BIO. TODO: investigate options to make it pass with HTTP BIO connector",
            getTomcatInstance().getConnector().getProtocolHandlerClassName().equals(
                    "org.apache.coyote.http11.Http11Protocol"));

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterFirehoseServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    clientEndpointConfig.getUserProperties().put(
            WsWebSocketContainer.SSL_TRUSTSTORE_PROPERTY,
            "test/org/apache/tomcat/util/net/ca.jks");
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("wss://localhost:" + getPort() +
                    TesterFirehoseServer.Config.PATH));

    // Process incoming messages very slowly
    MessageHandler handler = new SleepingText(5000);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    // Wait long enough for the buffers to fill and the send to timeout
    int count = 0;
    int limit = TesterFirehoseServer.WAIT_TIME_MILLIS / 100;

    System.err.println("Waiting for server to report an error");
    while (TesterFirehoseServer.Endpoint.getErrorCount() == 0 && count < limit) {
        Thread.sleep(100);
        count ++;
    }

    if (TesterFirehoseServer.Endpoint.getErrorCount() == 0) {
        Assert.fail("No error reported by Endpoint when timeout was expected");
    }

    // Wait up to another 20 seconds for the connection to be closed
    System.err.println("Waiting for connection to be closed");
    count = 0;
    limit = (TesterFirehoseServer.SEND_TIME_OUT_MILLIS * 4) / 100;
    while (TesterFirehoseServer.Endpoint.getOpenConnectionCount() != 0 && count < limit) {
        Thread.sleep(100);
        count ++;
    }

    int openConnectionCount = TesterFirehoseServer.Endpoint.getOpenConnectionCount();
    if (openConnectionCount != 0) {
        Assert.fail("There are [" + openConnectionCount + "] connections still open");
    }

    // Close the client session.
    wsSession.close();
}
 
Example 18
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testGetOpenSessions() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    EndpointA endpointA = new EndpointA();
    Session s1a = connectToEchoServer(wsContainer, endpointA,
            TesterEchoServer.Config.PATH_BASIC);
    Session s2a = connectToEchoServer(wsContainer, endpointA,
            TesterEchoServer.Config.PATH_BASIC);
    Session s3a = connectToEchoServer(wsContainer, endpointA,
            TesterEchoServer.Config.PATH_BASIC);

    EndpointB endpointB = new EndpointB();
    Session s1b = connectToEchoServer(wsContainer, endpointB,
            TesterEchoServer.Config.PATH_BASIC);
    Session s2b = connectToEchoServer(wsContainer, endpointB,
            TesterEchoServer.Config.PATH_BASIC);

    Set<Session> setA = s3a.getOpenSessions();
    Assert.assertEquals(3, setA.size());
    Assert.assertTrue(setA.remove(s1a));
    Assert.assertTrue(setA.remove(s2a));
    Assert.assertTrue(setA.remove(s3a));

    s1a.close();

    setA = s3a.getOpenSessions();
    Assert.assertEquals(2, setA.size());
    Assert.assertFalse(setA.remove(s1a));
    Assert.assertTrue(setA.remove(s2a));
    Assert.assertTrue(setA.remove(s3a));

    Set<Session> setB = s1b.getOpenSessions();
    Assert.assertEquals(2, setB.size());
    Assert.assertTrue(setB.remove(s1b));
    Assert.assertTrue(setB.remove(s2b));

    // Close sessions explicitly as Gump reports a session remains open at
    // the end of this test
    s2a.close();
    s3a.close();
    s1b.close();
    s2b.close();
}
 
Example 19
Source File: SocketSessionManager.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Broadcasts to a single client.
 * @return true only if message appears to have been sent
 */
public static boolean broadcastToClient(String message, String clientId) {
    Set<Session> invalidSessions = null;
    try {
        for (Map.Entry<String, ChannelInfo> channelEntry : channelMap.entrySet()) {
            for (Map.Entry<Session, ChannelInfo.ClientInfo> clientEntry : channelEntry.getValue().getClientMap().entrySet()) {
                Session session = clientEntry.getKey();
                if (clientId.equals(session.getId())) {
                    try {
                        if (session.isOpen()) {
                            session.getBasicRemote().sendText(message);
                            if (isDebug()) {
                                Debug.logInfo("Websocket: broadcasted message to client '" + clientId + "'", module);
                            }
                            return true;
                        } else {
                            if (invalidSessions == null) {
                                invalidSessions = new HashSet<>();
                            }
                            invalidSessions.add(session);
                        }
                    } catch (IOException e) {
                        if (invalidSessions == null) {
                            invalidSessions = new HashSet<>();
                        }
                        invalidSessions.add(session);
                        try {
                            session.close();
                        } catch (IOException ioe) {
                            if (isLog()) {
                                Debug.logError("Could not close websocket session: " + ioe.toString(), module);
                            }
                        }
                    }
                    return false;
                }
            }
        }
        return false;
    } finally {
        if (invalidSessions != null) {
            removeSessions(invalidSessions);
        }
    }
}
 
Example 20
Source File: TestEncodingDecoding.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
@Ignore // TODO Investigate why this test fails
public void testMessagesEndPoints() throws Exception {
    // Set up utility classes
    MessagesServer server = new MessagesServer();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(MessagesServer.class);

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ServerConfigListener.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    StringClient client = new StringClient();
    URI uri = new URI("ws://localhost:" + getPort() + PATH_MESSAGES_EP);
    Session session = wsContainer.connectToServer(client, uri);

    session.getBasicRemote().sendText(MESSAGE_ONE);

    // Should not take very long
    int i = 0;
    while (i < 20) {
        if (server.received.size() > 0 && client.received.size() > 0) {
            break;
        }
        i++;
        Thread.sleep(100);
    }

    // Check messages were received
    Assert.assertEquals(1, server.received.size());
    Assert.assertEquals(1, client.received.size());

    // Check correct messages were received
    Assert.assertEquals(MESSAGE_ONE, server.received.peek());
    session.close();

    Assert.assertNull(server.t);
}