Java Code Examples for org.springframework.web.socket.WebSocketSession#close()

The following examples show how to use org.springframework.web.socket.WebSocketSession#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: StompWebSocketIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void sendMessageToControllerAndReceiveReplyViaTopic() throws Exception {
	TextMessage message1 = create(StompCommand.SUBSCRIBE)
			.headers("id:subs1", "destination:/topic/increment").build();
	TextMessage message2 = create(StompCommand.SEND)
			.headers("destination:/app/increment").body("5").build();

	TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(1, message1, message2);
	WebSocketSession session = doHandshake(clientHandler, "/ws").get();

	try {
		assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));
	}
	finally {
		session.close();
	}
}
 
Example 2
Source File: TerminalHandler.java    From opencron with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
	super.handleTextMessage(session, message);
	try {
		getClient(session,null);
		if (this.terminalClient != null ) {
			if ( !terminalClient.isClosed()) {
				terminalClient.write(message.getPayload());
			}else {
				session.close();
			}
		}
	} catch (Exception e) {
		session.sendMessage(new TextMessage("Sorry! Opencron Terminal was closed, please try again. "));
		terminalClient.disconnect();
		session.close();
	}
}
 
Example 3
Source File: StompWebSocketIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void sendMessageToControllerAndReceiveReplyViaTopic() throws Exception {
	TextMessage m0 = create(StompCommand.CONNECT).headers("accept-version:1.1").build();
	TextMessage m1 = create(StompCommand.SUBSCRIBE)
			.headers("id:subs1", "destination:/topic/increment").build();
	TextMessage m2 = create(StompCommand.SEND)
			.headers("destination:/app/increment").body("5").build();

	TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(2, m0, m1, m2);
	WebSocketSession session = doHandshake(clientHandler, "/ws").get();

	try {
		assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));
	}
	finally {
		session.close();
	}
}
 
Example 4
Source File: StompWebSocketIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-10930
public void sendMessageToBrokerAndReceiveReplyViaTopic() throws Exception {
	TextMessage m0 = create(StompCommand.CONNECT).headers("accept-version:1.1").build();
	TextMessage m1 = create(StompCommand.SUBSCRIBE).headers("id:subs1", "destination:/topic/foo").build();
	TextMessage m2 = create(StompCommand.SEND).headers("destination:/topic/foo").body("5").build();

	TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(2, m0, m1, m2);
	WebSocketSession session = doHandshake(clientHandler, "/ws").get();

	try {
		assertTrue(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS));

		String payload = clientHandler.actual.get(1).getPayload();
		assertTrue("Expected STOMP MESSAGE, got " + payload, payload.startsWith("MESSAGE\n"));
	}
	finally {
		session.close();
	}
}
 
Example 5
Source File: WebSocketConfigurationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void registerWebSocketHandlerWithSockJS() throws Exception {
	WebSocketSession session = this.webSocketClient.doHandshake(
			new AbstractWebSocketHandler() {}, getWsBaseUrl() + "/sockjs/websocket").get();

	TestHandler serverHandler = this.wac.getBean(TestHandler.class);
	assertTrue(serverHandler.connectLatch.await(2, TimeUnit.SECONDS));

	session.close();
}
 
Example 6
Source File: SimpleClientWebSocketHandler.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")");
    session.close();
    this.messagePayload.set(message.getPayload());
    this.latch.countDown();
}
 
Example 7
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private void closeSession(WebSocketSession session) {
    try {
        clearSession(session);
        session.close();
    } catch (Exception e) {
        log.error("exception in close session", e);
    }
}
 
Example 8
Source File: TeapotHandler.java    From example-restful-project with MIT License 5 votes vote down vote up
/**
 * Assign IP address to teapot and registers it into command service.
 */
@Override
public void afterConnectionEstablished(WebSocketSession session)
        throws IOException {
    String teapotId = (String) session.getAttributes().get("teapotId");

    /* Registers the teapot first */
    commandService.register(teapotId, session);

    /* Find the teapot by id */
    // TODO: move this check into handshake handler
    try {
        Teapot teapot = crud.find(teapotId);

        /* Assign IP adress to the teapot */
        Inet4Address ip = (Inet4Address) InetAddress.getByAddress(new byte[] {
                (byte) 192, (byte) 168, (byte) 13, (byte) randomizer.nextInt(255)
        });

        teapot.setIp(ip);
        crud.update(teapotId, teapot);
    } catch (TeapotNotExistsException | TeapotAlreadyExistsException e) {

        /* Close websocket session */
        session.close(CloseStatus.NORMAL.withReason(e.getMessage()));

        e.printStackTrace();
    }
}
 
Example 9
Source File: MetricWsHandler.java    From artemis with Apache License 2.0 5 votes vote down vote up
private void remove(final WebSocketSession session) throws IOException {
    if (session == null) {
        return;
    }
    if (session.isOpen()) {
        session.close();
    }
    sessions.remove(session.getId());
}
 
Example 10
Source File: AbstractSockJsIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5000)
public void fallbackAfterConnectTimeout() throws Exception {
	TestClientHandler clientHandler = new TestClientHandler();
	this.testFilter.sleepDelayMap.put("/xhr_streaming", 10000L);
	this.testFilter.sendErrorMap.put("/xhr_streaming", 503);
	initSockJsClient(createXhrTransport());
	this.sockJsClient.setConnectTimeoutScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class));
	WebSocketSession clientSession = sockJsClient.doHandshake(clientHandler, this.baseUrl + "/echo").get();
	assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, clientSession.getClass());
	TextMessage message = new TextMessage("message1");
	clientSession.sendMessage(message);
	clientHandler.awaitMessage(message, 5000);
	clientSession.close();
}
 
Example 11
Source File: WebSocketStompClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void close() {
	WebSocketSession session = this.session;
	if (session != null) {
		try {
			session.close();
		}
		catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Failed to close session: " + session.getId(), ex);
			}
		}
	}
}
 
Example 12
Source File: StompWebSocketIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void sendMessageToController() throws Exception {
	TextMessage message = create(StompCommand.SEND).headers("destination:/app/simple").build();
	WebSocketSession session = doHandshake(new TestClientWebSocketHandler(0, message), "/ws").get();

	SimpleController controller = this.wac.getBean(SimpleController.class);
	try {
		assertTrue(controller.latch.await(TIMEOUT, TimeUnit.SECONDS));
	}
	finally {
		session.close();
	}
}
 
Example 13
Source File: BaseProxyHandler.java    From Jpom with MIT License 5 votes vote down vote up
@Override
public void destroy(WebSocketSession session) {
    try {
        if (session.isOpen()) {
            session.close();
        }
    } catch (IOException ignored) {
    }
    Map<String, Object> attributes = session.getAttributes();
    ProxySession proxySession = (ProxySession) attributes.get("proxySession");
    if (proxySession != null) {
        proxySession.close();
    }
}
 
Example 14
Source File: SubProtocolWebSocketHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * When a session is connected through a higher-level protocol it has a chance
 * to use heartbeat management to shut down sessions that are too slow to send
 * or receive messages. However, after a WebSocketSession is established and
 * before the higher level protocol is fully connected there is a possibility for
 * sessions to hang. This method checks and closes any sessions that have been
 * connected for more than 60 seconds without having received a single message.
 */
private void checkSessions() {
	long currentTime = System.currentTimeMillis();
	if (!isRunning() || (currentTime - this.lastSessionCheckTime < getTimeToFirstMessage())) {
		return;
	}

	if (this.sessionCheckLock.tryLock()) {
		try {
			for (WebSocketSessionHolder holder : this.sessions.values()) {
				if (holder.hasHandledMessages()) {
					continue;
				}
				long timeSinceCreated = currentTime - holder.getCreateTime();
				if (timeSinceCreated < getTimeToFirstMessage()) {
					continue;
				}
				WebSocketSession session = holder.getSession();
				if (logger.isInfoEnabled()) {
					logger.info("No messages received after " + timeSinceCreated + " ms. " +
							"Closing " + holder.getSession() + ".");
				}
				try {
					this.stats.incrementNoMessagesReceivedCount();
					session.close(CloseStatus.SESSION_NOT_RELIABLE);
				}
				catch (Throwable ex) {
					if (logger.isWarnEnabled()) {
						logger.warn("Failed to close unreliable " + session, ex);
					}
				}
			}
		}
		finally {
			this.lastSessionCheckTime = currentTime;
			this.sessionCheckLock.unlock();
		}
	}
}
 
Example 15
Source File: ConcurrentWebSocketSessionDecoratorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void closeStatusNormal() throws Exception {

	BlockingSession session = new BlockingSession();
	session.setOpen(true);
	WebSocketSession decorator = new ConcurrentWebSocketSessionDecorator(session, 10 * 1000, 1024);

	decorator.close(CloseStatus.PROTOCOL_ERROR);
	assertEquals(CloseStatus.PROTOCOL_ERROR, session.getCloseStatus());

	decorator.close(CloseStatus.SERVER_ERROR);
	assertEquals("Should have been ignored", CloseStatus.PROTOCOL_ERROR, session.getCloseStatus());
}
 
Example 16
Source File: TextWebSocketHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
	try {
		session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Binary messages not supported"));
	}
	catch (IOException ex) {
		// ignore
	}
}
 
Example 17
Source File: TextWebSocketHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
	try {
		session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Binary messages not supported"));
	}
	catch (IOException ex) {
		// ignore
	}
}
 
Example 18
Source File: WebSocketProxyTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
@WebsocketTest
public void shouldRouteWebSocketSession() throws Exception {
    final StringBuilder response = new StringBuilder();
    WebSocketSession session = appendingWebSocketSession(discoverableClientGatewayUrl(UPPERCASE_URL), response, 1);

    session.sendMessage(new TextMessage("hello world!"));
    synchronized (response) {
        response.wait(WAIT_TIMEOUT_MS);
    }

    assertEquals("HELLO WORLD!", response.toString());
    session.close();
}
 
Example 19
Source File: ApolloProtocolHandler.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    session.close(CloseStatus.SERVER_ERROR);
    cancelAll();
}
 
Example 20
Source File: AllServicesChangeWsHandler.java    From artemis with Apache License 2.0 4 votes vote down vote up
@Override
public boolean publish(final InstanceChange instanceChange) {
    try {
        if ((instanceChange == null) || (instanceChange.getInstance() == null)) {
            return true;
        }

        final String serviceId = instanceChange.getInstance().getServiceId();
        if (StringValues.isNullOrWhitespace(serviceId)) {
            return true;
        }

        final String instanceId = instanceChange.getInstance().getInstanceId();
        final String changeType = instanceChange.getChangeType();

        if (MapValues.isNullOrEmpty(sessions)) {
            return true;
        }
        final TextMessage message = new TextMessage(JacksonJsonSerializer.INSTANCE.serialize(instanceChange));
        List<WebSocketSession> allSessions = Lists.newArrayList(sessions.values());
        for (final WebSocketSession session : allSessions) {
            if (session.isOpen()) {
                try {
                    synchronized(session){
                        session.sendMessage(message);
                        MetricLoggerHelper.logPublishEvent("success", serviceId, instanceId, changeType);
                    }
                } catch (final Exception sendException) {
                    MetricLoggerHelper.logPublishEvent("failed", serviceId, instanceId, changeType);
                    logger.error("websocket session send message failed", sendException);
                    try{
                        session.close();
                    } catch (final Exception closeException) {
                        logger.warn("close websocket session failed", closeException);
                    }
                }
            }
        }
        logger.info(String.format("send instance change message to %d sessions: %s", sessions.size(), instanceChange));
        return true;
    } catch (final Exception e) {
        logger.error("send instance change failed", e);
        return false;
    }
}