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 File: SockJsSessionTests.java From java-technology-stack with MIT License | 6 votes |
@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 #2
Source File: SockJsSessionTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #3
Source File: DeviceHiveWebSocketHandler.java From devicehive-java-server with Apache License 2.0 | 6 votes |
@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 #4
Source File: SubProtocolWebSocketHandler.java From spring-analysis-note with MIT License | 6 votes |
@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 #5
Source File: SockJsSessionTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #6
Source File: WebSocketServerSockJsSession.java From java-technology-stack with MIT License | 6 votes |
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 File: WebSocketServerSockJsSession.java From spring4-understanding with Apache License 2.0 | 6 votes |
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 #8
Source File: WebSocketStompClientTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #9
Source File: WebSocketStompClientTests.java From java-technology-stack with MIT License | 6 votes |
@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 #10
Source File: HtmlFileTransportHandler.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #11
Source File: MyWebSocketHandler.java From albert with MIT License | 6 votes |
/** * 关闭连接后 */ 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 #12
Source File: WebSocketServerHandler.java From redtorch with MIT License | 6 votes |
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 #13
Source File: SockJsSessionTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #14
Source File: WebSocketServerSockJsSession.java From spring-analysis-note with MIT License | 6 votes |
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 #15
Source File: DeviceHiveWebSocketHandler.java From devicehive-java-server with Apache License 2.0 | 6 votes |
@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 #16
Source File: ClientSockJsSessionTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void close() throws Exception { this.session.handleFrame(SockJsFrame.openFrame().getContent()); this.session.close(); assertThat(this.session.isOpen(), equalTo(false)); assertThat(this.session.disconnectStatus, equalTo(CloseStatus.NORMAL)); verify(this.handler).afterConnectionEstablished(this.session); verifyNoMoreInteractions(this.handler); }
Example #17
Source File: LoggingWebSocketHandlerDecorator.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { if (logger.isDebugEnabled()) { logger.debug(session + " closed with " + closeStatus); } super.afterConnectionClosed(session, closeStatus); }
Example #18
Source File: WebSocketProxyServerHandler.java From api-layer with Eclipse Public License 2.0 | 5 votes |
private void openWebSocketConnection(RoutedService service, ServiceInstance serviceInstance, Object uri, String path, WebSocketSession webSocketSession) throws IOException { String serviceUrl = service.getServiceUrl(); String targetUrl = getTargetUrl(serviceUrl, serviceInstance, path); log.debug(String.format("Opening routed WebSocket session from %s to %s with %s by %s", uri.toString(), targetUrl, jettySslContextFactory, this)); try { WebSocketRoutedSession session = webSocketRoutedSessionFactory.session(webSocketSession, targetUrl, jettySslContextFactory); routedSessions.put(webSocketSession.getId(), session); } catch (WebSocketProxyError e) { log.debug("Error opening WebSocket connection to {}: {}", targetUrl, e.getMessage()); webSocketSession.close(CloseStatus.NOT_ACCEPTABLE.withReason(e.getMessage())); } }
Example #19
Source File: JsonRpcWebSocketHandler.java From kurento-java with Apache License 2.0 | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession wsSession, CloseStatus status) throws Exception { numConnections.decrementAndGet(); try { ServerSession session = (ServerSession) protocolManager.getSessionByTransportId(wsSession.getId()); if (session != null) { if (session.isGracefullyClosed()) { log.debug("{} WebSocket session {} with transportId {} closed gracefully", label, session.getSessionId(), wsSession.getId()); } else { log.debug( "{} WebSocket session {} with transportId {} closed for {} (code {}, reason '{}')", label, session.getSessionId(), wsSession.getId(), CloseStatusHelper.getCloseStatusType(status.getCode()), status.getCode(), status.getReason()); protocolManager.closeSessionIfTimeout(wsSession.getId(), status.getReason()); } } else { log.debug( "{} WebSocket session not associated to any jsonRpcSession " + "with transportId {} closed for {} (code {}, reason '{}')", label, wsSession.getId(), CloseStatusHelper.getCloseStatusType(status.getCode()), status.getCode(), status.getReason()); } } catch (Throwable t) { log.error("{} Exception processing afterConnectionClosed in session={}", label, wsSession.getId(), t); } }
Example #20
Source File: TeapotHandler.java From example-restful-project with MIT License | 5 votes |
/** * 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 #21
Source File: SubProtocolWebSocketHandler.java From java-technology-stack with MIT License | 5 votes |
/** * 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 #22
Source File: SessionDisconnectEvent.java From spring-analysis-note with MIT License | 5 votes |
/** * Create a new SessionDisconnectEvent. * @param source the component that published the event (never {@code null}) * @param message the message (never {@code null}) * @param sessionId the disconnect message * @param closeStatus the status object * @param user the current session user */ public SessionDisconnectEvent(Object source, Message<byte[]> message, String sessionId, CloseStatus closeStatus, @Nullable Principal user) { super(source, message, user); Assert.notNull(sessionId, "Session id must not be null"); this.sessionId = sessionId; this.status = closeStatus; }
Example #23
Source File: WebSocketTransportHandler.java From java-technology-stack with MIT License | 5 votes |
@Override public void handleRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, SockJsSession wsSession) throws SockJsException { WebSocketServerSockJsSession sockJsSession = (WebSocketServerSockJsSession) wsSession; try { wsHandler = new SockJsWebSocketHandler(getServiceConfig(), wsHandler, sockJsSession); this.handshakeHandler.doHandshake(request, response, wsHandler, sockJsSession.getAttributes()); } catch (Throwable ex) { sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR); throw new SockJsTransportFailureException("WebSocket handshake failure", wsSession.getId(), ex); } }
Example #24
Source File: SocketHandler.java From SpringBootBucket with MIT License | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { if (session.isOpen()) { session.close(); } sessions.remove(session); logger.info(String.format("Session %s closed because of %s", session.getId(), status.getReason())); }
Example #25
Source File: JettyXhrTransport.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void onFailure(Response response, Throwable failure) { if (connectFuture.setException(failure)) { return; } if (this.sockJsSession.isDisconnected()) { this.sockJsSession.afterTransportClosed(null); } else { this.sockJsSession.handleTransportError(failure); this.sockJsSession.afterTransportClosed(new CloseStatus(1006, failure.getMessage())); } }
Example #26
Source File: RestTemplateXhrTransport.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override protected void connectInternal(final TransportRequest transportRequest, final WebSocketHandler handler, final URI receiveUrl, final HttpHeaders handshakeHeaders, final XhrClientSockJsSession session, final SettableListenableFuture<WebSocketSession> connectFuture) { getTaskExecutor().execute(new Runnable() { @Override public void run() { HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders(); XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders); XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders); XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session); while (true) { if (session.isDisconnected()) { session.afterTransportClosed(null); break; } try { if (logger.isTraceEnabled()) { logger.trace("Starting XHR receive request, url=" + receiveUrl); } getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor); requestCallback = requestCallbackAfterHandshake; } catch (Throwable ex) { if (!connectFuture.isDone()) { connectFuture.setException(ex); } else { session.handleTransportError(ex); session.afterTransportClosed(new CloseStatus(1006, ex.getMessage())); } break; } } } }); }
Example #27
Source File: ExceptionWebSocketHandlerDecorator.java From java-technology-stack with MIT License | 5 votes |
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 #28
Source File: RestTemplateXhrTransportTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void connectReceiveAndClose() throws Exception { String body = "o\n" + "a[\"foo\"]\n" + "c[3000,\"Go away!\"]"; ClientHttpResponse response = response(HttpStatus.OK, body); connect(response); verify(this.webSocketHandler).afterConnectionEstablished(any()); verify(this.webSocketHandler).handleMessage(any(), eq(new TextMessage("foo"))); verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!"))); verifyNoMoreInteractions(this.webSocketHandler); }
Example #29
Source File: ConcurrentWebSocketSessionDecoratorTests.java From java-technology-stack with MIT License | 5 votes |
@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 #30
Source File: AbstractSockJsSession.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Invoked when the underlying connection is closed. */ public final void delegateConnectionClosed(CloseStatus status) throws Exception { if (!isClosed()) { try { updateLastActiveTime(); cancelHeartbeat(); } finally { this.state = State.CLOSED; this.handler.afterConnectionClosed(this, status); } } }