org.springframework.web.socket.CloseStatus Java Examples

The following examples show how to use org.springframework.web.socket.CloseStatus. 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 Project: devicehive-java-server   Author: devicehive   File: DeviceHiveWebSocketHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    CopyOnWriteArraySet<SubscriptionInfo> commandSubscriptions = (CopyOnWriteArraySet)
            session.getAttributes().get(CommandHandlers.SUBSCRIPTION_SET_NAME);
    commandService.sendUnsubscribeRequest(commandSubscriptions.stream()
            .map(SubscriptionInfo::getSubscriptionId).collect(Collectors.toSet()));

    CopyOnWriteArraySet<SubscriptionInfo> notificationSubscriptions = (CopyOnWriteArraySet)
            session.getAttributes().get(NotificationHandlers.SUBSCRIPTION_SET_NAME);
    notificationService.unsubscribe(notificationSubscriptions.stream()
            .map(SubscriptionInfo::getSubscriptionId).collect(Collectors.toSet()));

    sessionMonitor.removeSession(session.getId());

    if(session.isOpen()) {
        session.close();
    }
    logger.info("Websocket Connection Closed: session id {}, close status is {} ", session.getId(), status);
}
 
Example #2
Source Project: spring-analysis-note   Author: Vip-Augus   File: SockJsSessionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void closeWithWriteFrameExceptions() throws Exception {
	this.session.setExceptionOnWrite(new IOException());

	this.session.delegateConnectionEstablished();
	this.session.setActive(true);
	this.session.close();

	assertEquals(new CloseStatus(3000, "Go away!"), this.session.getCloseStatus());
	assertClosed();
}
 
Example #3
Source Project: redtorch   Author: sun0x00   File: WebSocketServerHandler.java    License: MIT License 6 votes vote down vote up
public void closeByNodeId(int nodeId) {
	if (!nodeIdSessionIdMap.containsKey(nodeId)) {
		logger.warn("根据节点ID关闭会话警告,无法通过节点ID找到会话ID,节点ID:{}", nodeId);
		return;
	} else {
		String sessionId = nodeIdSessionIdMap.get(nodeId);
		ThreadSafeWebSocketSession session = sessionIdSessionMap.get(sessionId);
		if (session != null && session.isOpen()) {
			try {
				session.close(CloseStatus.NORMAL.withReason("管理服务主动关闭!"));
			} catch (IOException e) {
				logger.error("根据节点ID关闭会话警告,无法通过会话ID找到会话或会话已关闭,节点ID:{},会话ID:{}", nodeId, sessionId, e);
			}
		} else {

			logger.warn("根据节点ID关闭会话警告,无法通过会话ID找到会话或会话已关闭,节点ID:{},会话ID:{}", nodeId, sessionId);
		}
	}
}
 
Example #4
Source Project: spring-analysis-note   Author: Vip-Augus   File: WebSocketStompClientTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void cancelInactivityTasks() throws Exception {
	TcpConnection<byte[]> tcpConnection = getTcpConnection();

	ScheduledFuture future = mock(ScheduledFuture.class);
	given(this.taskScheduler.scheduleWithFixedDelay(any(), eq(1L))).willReturn(future);

	tcpConnection.onReadInactivity(mock(Runnable.class), 2L);
	tcpConnection.onWriteInactivity(mock(Runnable.class), 2L);

	this.webSocketHandlerCaptor.getValue().afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL);

	verify(future, times(2)).cancel(true);
	verifyNoMoreInteractions(future);
}
 
Example #5
Source Project: spring4-understanding   Author: langtianya   File: WebSocketServerSockJsSession.java    License: Apache License 2.0 6 votes vote down vote up
public void initializeDelegateSession(WebSocketSession session) {
	synchronized (this.initSessionLock) {
		this.webSocketSession = session;
		try {
			// Let "our" handler know before sending the open frame to the remote handler
			delegateConnectionEstablished();
			this.webSocketSession.sendMessage(new TextMessage(SockJsFrame.openFrame().getContent()));

			// Flush any messages cached in the mean time
			while (!this.initSessionCache.isEmpty()) {
				writeFrame(SockJsFrame.messageFrame(getMessageCodec(), this.initSessionCache.poll()));
			}
			scheduleHeartbeat();
			this.openFrameSent = true;
		}
		catch (Exception ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
		}
	}
}
 
Example #6
Source Project: java-technology-stack   Author: codeEngraver   File: WebSocketServerSockJsSession.java    License: MIT License 6 votes vote down vote up
public void handleMessage(TextMessage message, WebSocketSession wsSession) throws Exception {
	String payload = message.getPayload();
	if (StringUtils.isEmpty(payload)) {
		return;
	}
	String[] messages;
	try {
		messages = getSockJsServiceConfig().getMessageCodec().decode(payload);
	}
	catch (Throwable ex) {
		logger.error("Broken data received. Terminating WebSocket connection abruptly", ex);
		tryCloseWithSockJsTransportError(ex, CloseStatus.BAD_DATA);
		return;
	}
	if (messages != null) {
		delegateMessages(messages);
	}
}
 
Example #7
Source Project: java-technology-stack   Author: codeEngraver   File: SockJsSessionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void close() throws Exception {
	this.session.delegateConnectionEstablished();
	assertOpen();

	this.session.setActive(true);
	this.session.close();

	assertEquals(1, this.session.getSockJsFramesWritten().size());
	assertEquals(SockJsFrame.closeFrameGoAway(), this.session.getSockJsFramesWritten().get(0));

	assertEquals(1, this.session.getNumberOfLastActiveTimeUpdates());
	assertTrue(this.session.didCancelHeartbeat());

	assertEquals(new CloseStatus(3000, "Go away!"), this.session.getCloseStatus());
	assertClosed();
	verify(this.webSocketHandler).afterConnectionClosed(this.session, new CloseStatus(3000, "Go away!"));
}
 
Example #8
Source Project: albert   Author: pospospos2007   File: MyWebSocketHandler.java    License: MIT License 6 votes vote down vote up
/**
 * 关闭连接后
 */
public void afterConnectionClosed(WebSocketSession session,CloseStatus closeStatus) throws Exception {
	System.out.println("Websocket:" + session.getId() + "已经关闭");
	Iterator<Entry<Integer, WebSocketSession>> it = userSocketSessionMap.entrySet().iterator();
	// 移除当前用户的Socket会话
	while (it.hasNext()) {
		Entry<Integer, WebSocketSession> entry = it.next();
		if (entry.getValue().getId().equals(session.getId())) {
			userSocketSessionMap.remove(entry.getKey());
			System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
			String username=userService.getNameById(entry.getKey());
			Message msg = new Message();
			msg.setFrom(-2);//下线消息,用-2表示
			msg.setText(username);
			this.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
			break;
		}
	}
}
 
Example #9
Source Project: spring-analysis-note   Author: Vip-Augus   File: WebSocketServerSockJsSession.java    License: MIT License 6 votes vote down vote up
public void initializeDelegateSession(WebSocketSession session) {
	synchronized (this.initSessionLock) {
		this.webSocketSession = session;
		try {
			// Let "our" handler know before sending the open frame to the remote handler
			delegateConnectionEstablished();
			this.webSocketSession.sendMessage(new TextMessage(SockJsFrame.openFrame().getContent()));

			// Flush any messages cached in the mean time
			while (!this.initSessionCache.isEmpty()) {
				writeFrame(SockJsFrame.messageFrame(getMessageCodec(), this.initSessionCache.poll()));
			}
			scheduleHeartbeat();
			this.openFrameSent = true;
		}
		catch (Throwable ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
		}
	}
}
 
Example #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: SubProtocolWebSocketHandler.java    License: MIT License 6 votes vote down vote up
@Override
public final void stop() {
	synchronized (this.lifecycleMonitor) {
		this.running = false;
		this.clientOutboundChannel.unsubscribe(this);
	}

	// Proactively notify all active WebSocket sessions
	for (WebSocketSessionHolder holder : this.sessions.values()) {
		try {
			holder.getSession().close(CloseStatus.GOING_AWAY);
		}
		catch (Throwable ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Failed to close '" + holder.getSession() + "': " + ex);
			}
		}
	}
}
 
Example #11
Source Project: spring4-understanding   Author: langtianya   File: SockJsSessionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void close() throws Exception {

	this.session.delegateConnectionEstablished();
	assertOpen();

	this.session.setActive(true);
	this.session.close();

	assertEquals(1, this.session.getSockJsFramesWritten().size());
	assertEquals(SockJsFrame.closeFrameGoAway(), this.session.getSockJsFramesWritten().get(0));

	assertEquals(1, this.session.getNumberOfLastActiveTimeUpdates());
	assertTrue(this.session.didCancelHeartbeat());

	assertEquals(new CloseStatus(3000, "Go away!"), this.session.getCloseStatus());
	assertClosed();
	verify(this.webSocketHandler).afterConnectionClosed(this.session, new CloseStatus(3000, "Go away!"));
}
 
Example #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: SockJsSessionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void closeWhenNotOpen() throws Exception {
	assertNew();

	this.session.close();
	assertNull("Close not ignored for a new session", this.session.getCloseStatus());

	this.session.delegateConnectionEstablished();
	assertOpen();

	this.session.close();
	assertClosed();
	assertEquals(3000, this.session.getCloseStatus().getCode());

	this.session.close(CloseStatus.SERVER_ERROR);
	assertEquals("Close should be ignored if already closed", 3000, this.session.getCloseStatus().getCode());
}
 
Example #13
Source Project: devicehive-java-server   Author: devicehive   File: DeviceHiveWebSocketHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    logger.error("Error in session {}: {}", session.getId(), exception.getMessage());
    if (exception.getMessage().contains("Connection reset by peer")) {
        afterConnectionClosed(session, CloseStatus.SESSION_NOT_RELIABLE);
        return;
    }

    JsonMessageBuilder builder;
    session = sessionMonitor.getSession(session.getId());

    if (exception instanceof JsonParseException) {
        builder = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, "Incorrect JSON syntax");
    } else {
        builder = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    }
    try {
        session.sendMessage(new TextMessage(GsonFactory.createGson().toJson(builder.build())));
    } catch (ClosedChannelException closedChannelException) {
        logger.error("WebSocket error: Channel is closed");
    }
}
 
Example #14
Source Project: java-technology-stack   Author: codeEngraver   File: WebSocketStompClientTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void cancelInactivityTasks() throws Exception {
	TcpConnection<byte[]> tcpConnection = getTcpConnection();

	ScheduledFuture future = mock(ScheduledFuture.class);
	when(this.taskScheduler.scheduleWithFixedDelay(any(), eq(1L))).thenReturn(future);

	tcpConnection.onReadInactivity(mock(Runnable.class), 2L);
	tcpConnection.onWriteInactivity(mock(Runnable.class), 2L);

	this.webSocketHandlerCaptor.getValue().afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL);

	verify(future, times(2)).cancel(true);
	verifyNoMoreInteractions(future);
}
 
Example #15
Source Project: spring4-understanding   Author: langtianya   File: HtmlFileTransportHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		AbstractHttpSockJsSession sockJsSession) throws SockJsException {

	String callback = getCallbackParam(request);
	if (!StringUtils.hasText(callback)) {
		response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
		try {
			response.getBody().write("\"callback\" parameter required".getBytes(UTF8_CHARSET));
		}
		catch (IOException ex) {
			sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
			throw new SockJsTransportFailureException("Failed to write to response", sockJsSession.getId(), ex);
		}
		return;
	}

	super.handleRequestInternal(request, response, sockJsSession);
}
 
Example #16
Source Project: spring4ws-demos   Author: ralscha   File: Snake.java    License: Apache License 2.0 5 votes vote down vote up
protected void sendMessage(String msg) {

		try {
			this.session.sendMessage(new TextMessage(msg));
		}
		catch (IOException ioe) {
			try {
				this.session.close(CloseStatus.NO_CLOSE_FRAME);
			}
			catch (IOException ioe2) {
				// Ignore
			}
		}
	}
 
Example #17
Source Project: spring4-understanding   Author: langtianya   File: WebSocketServerSockJsSession.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void disconnect(CloseStatus status) throws IOException {
	synchronized (this) {
		if (isActive()) {
			this.disconnected = true;
			this.webSocketSession.close(status);
		}
	}
}
 
Example #18
Source Project: java-technology-stack   Author: codeEngraver   File: ConcurrentWebSocketSessionDecorator.java    License: MIT License 5 votes vote down vote up
@Override
public void close(CloseStatus status) throws IOException {
	this.closeLock.lock();
	try {
		if (this.closeInProgress) {
			return;
		}
		if (!CloseStatus.SESSION_NOT_RELIABLE.equals(status)) {
			try {
				checkSessionLimits();
			}
			catch (SessionLimitExceededException ex) {
				// Ignore
			}
			if (this.limitExceeded) {
				if (logger.isDebugEnabled()) {
					logger.debug("Changing close status " + status + " to SESSION_NOT_RELIABLE.");
				}
				status = CloseStatus.SESSION_NOT_RELIABLE;
			}
		}
		this.closeInProgress = true;
		super.close(status);
	}
	finally {
		this.closeLock.unlock();
	}
}
 
Example #19
Source Project: spring-analysis-note   Author: Vip-Augus   File: WebSocketServerSockJsSessionTests.java    License: MIT License 5 votes vote down vote up
@Test
public void disconnect() throws Exception {

	this.session.initializeDelegateSession(this.webSocketSession);
	this.session.close(CloseStatus.NOT_ACCEPTABLE);

	assertEquals(CloseStatus.NOT_ACCEPTABLE, this.webSocketSession.getCloseStatus());
}
 
Example #20
Source Project: spring-analysis-note   Author: Vip-Augus   File: ExceptionWebSocketHandlerDecorator.java    License: MIT License 5 votes vote down vote up
public static void tryCloseWithError(WebSocketSession session, Throwable exception, Log logger) {
	if (logger.isErrorEnabled()) {
		logger.error("Closing session due to exception for " + session, exception);
	}
	if (session.isOpen()) {
		try {
			session.close(CloseStatus.SERVER_ERROR);
		}
		catch (Throwable ex) {
			// ignore
		}
	}
}
 
Example #21
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
public void onFailure(Throwable failure) {
	IoUtils.safeClose(this.connection);
	if (this.connectFuture.setException(failure)) {
		return;
	}
	if (this.session.isDisconnected()) {
		this.session.afterTransportClosed(null);
	}
	else {
		this.session.handleTransportError(failure);
		this.session.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
	}
}
 
Example #22
Source Project: redtorch   Author: sun0x00   File: RtWebSocketClient.java    License: MIT License 5 votes vote down vote up
public void clsoe(CloseStatus closeStatus) {
	try {
		if (webSocketSession != null) {
			webSocketSession.close(closeStatus);
		}
	} catch (Exception e) {
		logger.error("关闭连接错误", e);
	}
}
 
Example #23
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractWebSocketSession.java    License: MIT License 5 votes vote down vote up
@Override
public final void close(CloseStatus status) throws IOException {
	checkNativeSessionInitialized();
	if (logger.isDebugEnabled()) {
		logger.debug("Closing " + this);
	}
	closeInternal(status);
}
 
Example #24
Source Project: haven-platform   Author: codeabovelab   File: WsTtyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
    TtyProxy tty = TtyProxy.get(session);
    if(tty != null) {
        tty.closeCausedFront();
    }

}
 
Example #25
Source Project: paas   Author: jitwxs   File: ContainerExecWSHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * webSocket关闭后关闭线程
 * @author jitwxs
 * @since 2018/7/1 14:22
 */
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    String containerId = session.getAttributes().get("containerId").toString();
    ExecSession execSession = execSessionMap.get(containerId);
    if (execSession != null) {
        execSession.getOutPutThread().interrupt();
    }
}
 
Example #26
Source Project: spring4-understanding   Author: langtianya   File: BinaryWebSocketHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
	try {
		session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Text messages not supported"));
	}
	catch (IOException e) {
		// ignore
	}
}
 
Example #27
Source Project: spring4-understanding   Author: langtianya   File: SubProtocolWebSocketHandlerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void checkSession() throws Exception {
	TestWebSocketSession session1 = new TestWebSocketSession("id1");
	TestWebSocketSession session2 = new TestWebSocketSession("id2");
	session1.setOpen(true);
	session2.setOpen(true);
	session1.setAcceptedProtocol("v12.stomp");
	session2.setAcceptedProtocol("v12.stomp");

	this.webSocketHandler.setProtocolHandlers(Arrays.asList(this.stompHandler));
	this.webSocketHandler.afterConnectionEstablished(session1);
	this.webSocketHandler.afterConnectionEstablished(session2);

	DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(this.webSocketHandler);
	Map<String, ?> map = (Map<String, ?>) handlerAccessor.getPropertyValue("sessions");
	DirectFieldAccessor session1Accessor = new DirectFieldAccessor(map.get("id1"));
	DirectFieldAccessor session2Accessor = new DirectFieldAccessor(map.get("id2"));

	long sixtyOneSecondsAgo = System.currentTimeMillis() - 61 * 1000;
	handlerAccessor.setPropertyValue("lastSessionCheckTime", sixtyOneSecondsAgo);
	session1Accessor.setPropertyValue("createTime", sixtyOneSecondsAgo);
	session2Accessor.setPropertyValue("createTime", sixtyOneSecondsAgo);

	this.webSocketHandler.start();
	this.webSocketHandler.handleMessage(session1, new TextMessage("foo"));

	assertTrue(session1.isOpen());
	assertNull(session1.getCloseStatus());

	assertFalse(session2.isOpen());
	assertEquals(CloseStatus.SESSION_NOT_RELIABLE, session2.getCloseStatus());

	assertNotEquals("lastSessionCheckTime not updated", sixtyOneSecondsAgo,
			handlerAccessor.getPropertyValue("lastSessionCheckTime"));
}
 
Example #28
Source Project: redtorch   Author: sun0x00   File: WebSocketServerHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws InterruptedException, IOException {
	int nodeId = (int) session.getAttributes().get(RtConstant.KEY_NODE_ID);
	logger.warn("接收到文本消息,节点ID:{},会话ID:{}", nodeId, session.getId());
	try {
		session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Text messages not supported!"));
	} catch (Exception e) {
		logger.error("关闭异常", e);
	}
}
 
Example #29
Source Project: java-technology-stack   Author: codeEngraver   File: PerConnectionWebSocketHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
	try {
		getHandler(session).afterConnectionClosed(session, closeStatus);
	}
	finally {
		destroyHandler(session);
	}
}
 
Example #30
Source Project: spring4-understanding   Author: langtianya   File: ExceptionWebSocketHandlerDecorator.java    License: Apache License 2.0 5 votes vote down vote up
public static void tryCloseWithError(WebSocketSession session, Throwable exception, Log logger) {
	if (logger.isDebugEnabled()) {
		logger.debug("Closing due to exception for " + session, exception);
	}
	if (session.isOpen()) {
		try {
			session.close(CloseStatus.SERVER_ERROR);
		}
		catch (Throwable ex) {
			// ignore
		}
	}
}