List of usage examples for org.springframework.web.socket WebSocketSession close
void close(CloseStatus status) throws IOException;
From source file:com.github.mrstampy.gameboot.otp.websocket.OtpClearWebSocketHandler.java
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { try {// w ww . j a va 2s . c o m session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Text messages not supported")); } catch (IOException e) { // ignore } }
From source file:samples.websocket.behavoir.CloseWithCodeWebSocketHandler.java
@Override protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception { byte[] payload = message.getPayload().array(); switch (payload.length) { case 4: {/*from w ww .j a v a2s . c o m*/ int ir = 0; for (int i = 0; i < 4; ++i) ir += (payload[i] & 0xff) << 8 * i; session.close(new CloseStatus(ir)); } break; case 8: { long lr = 0; for (int i = 0; i < 8; ++i) lr += (long) (payload[i] & 0xff) << 8 * i; session.close(new CloseStatus((int) lr)); } break; default: session.sendMessage(new TextMessage("unable to parse close code")); break; } }
From source file:com.navercorp.pinpoint.web.websocket.ActiveThreadCountHandler.java
private void closeSession(WebSocketSession session, CloseStatus status) { try {//from ww w. j a v a 2 s .c o m session.close(status); } catch (Exception e) { logger.warn(e.getMessage(), e); } }
From source file:com.zb.app.websocket.server.WebSocketServerHandler.java
/** * ?WebSocketSession,Session/*from w w w . ja v a2 s .c o m*/ * * @param session Session */ public void removeSession(WebSocketSession session) { SessionWrapper sw = getSessionInfo(session); if (sw == null || StringUtils.isEmpty(sw.getId())) { return; } ClientWrapper clientInfo = sw.getClientInfo(); String sessionId = sw.getId(); String ip = clientInfo.getIp(); Long mId = clientInfo.getmId(); try { session.close(CloseStatus.NORMAL); logger.error("WebSocketServerHandler removeSession() successfull! mid={},sessionId={},ip={}", mId, sessionId, ip); } catch (Exception e) { if (session != null && !session.isOpen()) { logger.error( "WebSocketServerHandler removeSession() is Normally closed! mid={},sessionId={},ip={}", mId, sessionId, ip); } else { logger.error("WebSocketServerHandler removeSession() faild! mid={},sessionId={},ip={}", mId, sessionId, ip); } } finally { Set<SessionWrapper> set = sessionCacheMap.get(clientInfo); set.remove(sw); if (Argument.isEmpty(set)) { sessionCacheMap.remove(clientInfo); } } }
From source file:ch.rasc.wampspring.config.WampSubProtocolHandler.java
/** * Handle WAMP messages going back out to WebSocket clients. *//*from w w w .ja v a2s .c o m*/ @Override public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message instanceof WampMessage)) { logger.error("Expected WampMessage. Ignoring " + message + "."); return; } boolean closeWebSocketSession = false; try { String json = ((WampMessage) message).toJson(this.jsonFactory); session.sendMessage(new TextMessage(json)); } catch (SessionLimitExceededException ex) { // Bad session, just get out throw ex; } catch (Throwable ex) { // Could be part of normal workflow (e.g. browser tab closed) logger.debug("Failed to send WebSocket message to client in session " + session.getId() + ".", ex); closeWebSocketSession = true; } finally { if (closeWebSocketSession) { try { session.close(CloseStatus.PROTOCOL_ERROR); } catch (IOException ex) { // Ignore } } } }
From source file:org.metis.push.PusherBean.java
@Override /**/*from w w w . j ava 2 s .com*/ * This method handles an incoming message from the web socket client. */ public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { if (session == null) { LOG.error(getBeanName() + ": null session"); throw new Exception(getBeanName() + ":handleTextMessage, null session was received"); } // the session should be in the registry WdsSocketSession wdsSession = getWdsSessions().get(session.getId()); if (wdsSession == null) { LOG.error(getBeanName() + ":handleTextMessage, session with this id is not in registry: " + session.getId()); session.close(new CloseStatus(SERVER_ERROR.getCode(), "ERROR, session with this id not in registry: " + session.getId())); return; } // some sort of message should have been received if (message == null) { LOG.error(getBeanName() + ":handleTextMessage, null message parameter"); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, session with this id gave a null message " + "parameter: " + session.getId())); return; } // we're supposed to receive a JSON object String jsonMsg = message.getPayload(); if (jsonMsg == null) { LOG.error(getBeanName() + ":handleTextMessage, getPayload returns null or empty string"); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, session with this id did not return a payload: " + session.getId())); return; } if (jsonMsg.isEmpty()) { LOG.error(getBeanName() + ":handleTextMessage, getPayload returns zero-length string"); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, session with this id returns zero-length payload: " + session.getId())); return; } // dump the request if trace is on if (LOG.isTraceEnabled()) { LOG.trace(getBeanName() + ":***** processing new request *****"); LOG.trace(getBeanName() + ":session id = " + session.getId()); LOG.trace(getBeanName() + ":session remote address = " + session.getRemoteAddress().toString()); LOG.trace(getBeanName() + ":session uri = " + session.getUri().toString()); LOG.trace(getBeanName() + ":session json object = " + jsonMsg); } // parse the json object List<Map<String, String>> jParams = null; try { jParams = Utils.parseJson(jsonMsg); } catch (Exception exc) { LOG.error(getBeanName() + ":caught this " + "exception while parsing json object: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } session.close(new CloseStatus(SERVER_ERROR.getCode(), "ERROR, got this json parsing exception: " + exc.getMessage())); return; } if (jParams == null || jParams.isEmpty()) { LOG.error(getBeanName() + ":json parser returns null or " + "empty json array"); session.close( new CloseStatus(SERVER_ERROR.getCode(), "ERROR, json parser returns null or empty json array")); return; } // if trace is on, dump the params (if any) to the log if (LOG.isDebugEnabled()) { LOG.debug( getBeanName() + ": handleRequestInternal, received these params: " + jParams.get(0).toString()); } // get the command portion of the json message Map<String, String> map = jParams.get(0); String command = map.remove(WS_COMMAND); if (command == null) { LOG.error(getBeanName() + ":command field not present"); session.close(POLICY_VIOLATION); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, command string not present or improperly set: " + command)); return; } if (!command.equals(WS_SUBSCRIBE) && !command.equals(WS_PING)) { LOG.error(getBeanName() + ":received this unknown command = " + command); session.close(POLICY_VIOLATION); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, received this unknown command = " + command)); return; } // Get the SQL Job, if any, that this session is currently subscribed to SqlJob job = wdsSession.getMyJob(); // if this is a ping command, return session's current subscription if (command.equals(WS_PING)) { LOG.debug(getBeanName() + ":received ping command"); List<Map<String, Object>> response = new ArrayList<Map<String, Object>>(); Map<String, Object> map0 = new HashMap<String, Object>(); if (job != null) { LOG.debug(getBeanName() + ": client is subscribed"); map0.put(WS_STATUS, WS_SUBSCRIBED); map = job.getParams(); if (map != null && !map.isEmpty()) { for (String key : map.keySet()) { map0.put(key, map.get(key)); } } } else { LOG.debug(getBeanName() + ": client is not subscribed"); map0.put(WS_STATUS, WS_OK); } response.add(map0); // send response back to client session.sendMessage(new TextMessage(Utils.generateJson(response))); return; } // find a sql statement that matches the incoming session request's // params SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null) : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if getMatch could not find a match, then return error to client if (sqlStmnt == null) { LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this map: " + map.toString()); List<Map<String, Object>> response = new ArrayList<Map<String, Object>>(); Map<String, Object> map0 = new HashMap<String, Object>(); if (map != null && !map.isEmpty()) { for (String key : map.keySet()) { map0.put(key, map.get(key)); } } map0.put(WS_STATUS, WS_NOT_FOUND); // send response back to client session.sendMessage(new TextMessage(Utils.generateJson(response))); return; } // other than a ping, the only other command from the client is a // subscription command // Does this session already exist in one of the sql jobs? Note that the // client can switch subscriptions. if (job != null) { // the session pertains to a job, but does that job's map match // that of this session's subscription request if (job.isParamMatch(map)) { // if so, we're done return; } else { // else remove this session from that job - the client is // switching subscriptions job.removeSession(wdsSession.getId()); } } mainLock.lock(); try { // if we've gotten this far, the session does not pertain to a job // or it is a subscription change. so we now need to find an // existing job whose params match that of the incoming session. if // no job was found, then create and start one if (sqlStmnt.findSqlJob(map, wdsSession) == null) { sqlStmnt.createSqlJob(map, wdsSession); } } finally { mainLock.unlock(); } }
From source file:org.metis.push.PusherBean.java
/** * This method is called by the web socket container after a new * connection/session has been established with this server endpoint. This * method will attempt to subscribe the client based on any query params and * if no params were provide, will use the URL's extra path info. */// w w w . ja va 2 s. c o m public void afterConnectionEstablished(WebSocketSession session) throws Exception { super.afterConnectionEstablished(session); LOG.debug(getBeanName() + ":afterConnectionEstablished - session id = " + session.getId()); // place the session in the global session registry. it will be removed // from the registry when it is closed WdsSocketSession wds = new WdsSocketSession(session); getWdsSessions().put(session.getId(), wds); // based on the query string (if any), attempt to find a SqlStmnt for // this session Map<String, String> map = Utils.getQueryMap(session.getUri().getQuery()); SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null) : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if statement was not found and query params were provided, then // close connection because search for statement had to take place based // on query params provided. in other words, if client provides query // params then it is requesting a subscrption via those params. if (sqlStmnt == null && (map != null && !map.isEmpty())) { LOG.error(getBeanName() + ":afterConnectionEstablished - unable to find sql " + "statement with this incoming param set: " + map.toString()); session.close(POLICY_VIOLATION); return; } // if statement was not found and params were not provided, then attempt // to find statement based on the url's "extra path" info if (sqlStmnt == null) { LOG.trace(getBeanName() + ":afterConnectionEstablished - unable to find sql " + "statement on first pass, will attempt to use extra path info"); String[] xtraPathInfo = Utils.getExtraPathInfo(session.getUri().toString()); if (xtraPathInfo != null && xtraPathInfo.length >= 2) { LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]); // put the xtra path info in the bucket and try again map = (map == null) ? new HashMap<String, String>() : map; map.clear(); map.put(xtraPathInfo[0], xtraPathInfo[1]); // try again with the extra path info sqlStmnt = SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if statement could not be found, then simply return - client // may later subscribe with valid params if (sqlStmnt == null) { LOG.debug(getBeanName() + ":findStmnt - unable to find sql " + "statement with this xtra path info: " + map.toString()); return; } } else { // there was no extra path info, so simply return return; } } mainLock.lock(); try { // if we've gotten this far, a SqlStmnt was found based on query or // extra path info, now see if SqlStmnt already has a job with the // same param set (map). if no job was found, then create and start // one if (sqlStmnt.findSqlJob(map, wds) == null) { sqlStmnt.createSqlJob(map, wds); } } finally { mainLock.unlock(); } }
From source file:org.springframework.integration.websocket.IntegrationWebSocketContainer.java
public void closeSession(WebSocketSession session, CloseStatus closeStatus) throws Exception { // Session may be unresponsive so clear first session.close(closeStatus); this.webSocketHandler.afterConnectionClosed(session, closeStatus); }
From source file:org.springframework.integration.websocket.IntegrationWebSocketContainer.java
@Override public void destroy() throws Exception { try {/*w w w . j av a 2s. c om*/ // Notify sessions to stop flushing messages for (WebSocketSession session : this.sessions.values()) { try { session.close(CloseStatus.GOING_AWAY); } catch (Exception e) { this.logger.error("Failed to close session id '" + session.getId() + "': " + e.getMessage()); } } } finally { this.sessions.clear(); } }
From source file:org.springframework.messaging.simp.stomp.StompProtocolHandler.java
/** * Handle STOMP messages going back out to WebSocket clients. *///from w ww. java 2s. co m @Override public void handleMessageToClient(WebSocketSession session, Message<?> message) { StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); headers.setCommandIfNotSet(StompCommand.MESSAGE); if (StompCommand.CONNECTED.equals(headers.getCommand())) { // Ignore for now since we already sent it return; } if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) { // TODO: failed message delivery mechanism logger.error("Ignoring message, no subscriptionId header: " + message); return; } if (!(message.getPayload() instanceof byte[])) { // TODO: failed message delivery mechanism logger.error("Ignoring message, expected byte[] content: " + message); return; } try { message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build(); byte[] bytes = this.stompMessageConverter.fromMessage(message); session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8")))); } catch (Throwable t) { sendErrorMessage(session, t); } finally { if (StompCommand.ERROR.equals(headers.getCommand())) { try { session.close(CloseStatus.PROTOCOL_ERROR); } catch (IOException e) { } } } }