Java Code Examples for org.springframework.web.socket.WebSocketSession#getId()
The following examples show how to use
org.springframework.web.socket.WebSocketSession#getId() .
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: Handler.java From kurento-tutorial-java with Apache License 2.0 | 6 votes |
private synchronized void sendMessage(final WebSocketSession session, String message) { log.debug("[Handler::sendMessage] {}", message); if (!session.isOpen()) { log.warn("[Handler::sendMessage] Skip, WebSocket session isn't open"); return; } final String sessionId = session.getId(); if (!users.containsKey(sessionId)) { log.warn("[Handler::sendMessage] Skip, unknown user, id: {}", sessionId); return; } try { session.sendMessage(new TextMessage(message)); } catch (IOException ex) { log.error("[Handler::sendMessage] Exception: {}", ex.getMessage()); } }
Example 2
Source File: Handler.java From kurento-tutorial-java with Apache License 2.0 | 6 votes |
private void handleAddIceCandidate(final WebSocketSession session, JsonObject jsonMessage) { final String sessionId = session.getId(); if (!users.containsKey(sessionId)) { log.warn("[Handler::handleAddIceCandidate] Skip, unknown user, id: {}", sessionId); return; } final UserSession user = users.get(sessionId); final JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject(); final IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").getAsString(), jsonCandidate.get("sdpMid").getAsString(), jsonCandidate.get("sdpMLineIndex").getAsInt()); WebRtcEndpoint webRtcEp = user.getWebRtcEndpoint(); webRtcEp.addIceCandidate(candidate); }
Example 3
Source File: ServiceChangeWsHandler.java From artemis with Apache License 2.0 | 6 votes |
/** * @param discoveryConfig * @param session */ private void add(final DiscoveryConfig discoveryConfig, final WebSocketSession session) { if ((discoveryConfig == null) || (session == null)) { return; } final String serviceId = discoveryConfig.getServiceId(); final String sessionId = session.getId(); if (StringValues.isNullOrWhitespace(serviceId) || StringValues.isNullOrWhitespace(sessionId)) { return; } Set<String> sessionIds = serviceChangeSessions.get(serviceId); if (sessionIds == null) { synchronized(ServiceChangeWsHandler.class) { sessionIds = serviceChangeSessions.get(serviceId); if (sessionIds == null) { sessionIds = Sets.newConcurrentHashSet(); serviceChangeSessions.put(serviceId, sessionIds); } } } sessionIds.add(sessionId); }
Example 4
Source File: Handler.java From kurento-tutorial-java with Apache License 2.0 | 6 votes |
private void stop(final WebSocketSession session) { log.info("[Handler::stop]"); // Update the UI sendPlayEnd(session); // Remove the user session and release all resources String sessionId = session.getId(); UserSession user = users.remove(sessionId); if (user != null) { MediaPipeline mediaPipeline = user.getMediaPipeline(); if (mediaPipeline != null) { log.info("[Handler::stop] Release the Media Pipeline"); mediaPipeline.release(); } } }
Example 5
Source File: GameHandler.java From computoser with GNU Affero General Public License v3.0 | 6 votes |
private void join(String gameId, String playerName, WebSocketSession session) { Game game = games.get(gameId); if (game == null) { sendMessage(new GameEvent(GameEventType.NO_GAME_AVAILABLE), session); } if (!game.isStarted()) { String playerId = session.getId(); Player player = players.get(playerId); player.setName(playerName); playerGames.put(playerId, game); if (!game.playerJoined(player)) { sendMessage(new GameEvent(GameEventType.PLAYER_NAME_TAKEN), session); } } else { sendMessage(new GameEvent(GameEventType.GAME_ALREADY_STARTED), session); } }
Example 6
Source File: CallHandler.java From kurento-tutorial-java with Apache License 2.0 | 5 votes |
public void stop(WebSocketSession session) throws IOException { String sessionId = session.getId(); if (pipelines.containsKey(sessionId)) { pipelines.get(sessionId).release(); CallMediaPipeline pipeline = pipelines.remove(sessionId); pipeline.release(); // Both users can stop the communication. A 'stopCommunication' // message will be sent to the other peer. UserSession stopperUser = registry.getBySession(session); if (stopperUser != null) { UserSession stoppedUser = (stopperUser.getCallingFrom() != null) ? registry.getByName(stopperUser .getCallingFrom()) : stopperUser.getCallingTo() != null ? registry .getByName(stopperUser.getCallingTo()) : null; if (stoppedUser != null) { JsonObject message = new JsonObject(); message.addProperty("id", "stopCommunication"); stoppedUser.sendMessage(message); stoppedUser.clear(); } stopperUser.clear(); } } }
Example 7
Source File: PluginHandler.java From TrackRay with GNU General Public License v3.0 | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { log.info("connect websocket closed......."); String id = session.getId(); kill(id); super.afterConnectionClosed(session, closeStatus); }
Example 8
Source File: NodeSession.java From java-trader with Apache License 2.0 | 5 votes |
NodeSession(NodeMgmtServiceImpl nodeMgmtService, WebSocketSession wsSession){ this.nodeMgmtService = nodeMgmtService; this.wsSession = wsSession; this.wsState = SessionState.Initializing; wsId = wsSession.getId(); creationTime = System.currentTimeMillis(); }
Example 9
Source File: WebSocketServerHandler.java From redtorch with MIT License | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { String sessionId = session.getId(); int nodeId = (int) session.getAttributes().get(RtConstant.KEY_NODE_ID); if (sessionIdNodeIdMap.containsKey(sessionId)) { logger.info("连接已关闭,节点ID:{},会话ID:{}", nodeId, sessionId); sessionIdSessionMap.remove(sessionId); nodeIdSessionIdMap.remove(nodeId); sessionIdNodeIdMap.remove(sessionId); masterSystemService.removeGatewayIdByNodeId(nodeId); masterTradeExecuteService.removeSubscribeRelationByNodeId(nodeId); skipLoginNodeIdSet.remove(nodeId); skipTradeEventsNodeIdSet.remove(nodeId); String operatorId = nodeIdOperatorIdMap.remove(nodeId); synchronized (operatorIdNodeIdSetMap) { Set<Integer> nodeIdSet = operatorIdNodeIdSetMap.get(operatorId); if (nodeIdSet != null) { nodeIdSet.remove(nodeId); } if (nodeIdSet != null && nodeIdSet.isEmpty()) { operatorIdNodeIdSetMap.remove(operatorId); } } var dataQueue = nodeIdDataQueueMap.remove(nodeId); if (dataQueue != null) { byte[] shutdownData = new byte[] { 0 }; dataQueue.put(shutdownData); } if (session.getAttributes().get(WebSocketConstant.KEY_AUTHED) != null && (boolean) session.getAttributes().get(WebSocketConstant.KEY_AUTHED)) { nodeService.updateNodeLogoutInfo(nodeId); } } else { logger.info("连接已关闭,连接未认证,节点ID:{},会话ID:{}", nodeId, sessionId); } }
Example 10
Source File: TeapotCommandServiceImpl.java From example-restful-project with MIT License | 5 votes |
/** {@inheritDoc} */ @Override public synchronized void register(String teapotId, WebSocketSession session) { String sessionId = session.getId(); sessionRepository.save(session); mapTeapotIdSessionId.put(teapotId, sessionId); mapSessionIdTeapotId.put(sessionId, teapotId); }
Example 11
Source File: Handler.java From kurento-tutorial-java with Apache License 2.0 | 5 votes |
/** * Invoked when a new WebSocket message arrives. */ @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { final String sessionId = session.getId(); JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class); log.info("[Handler::handleTextMessage] message: {}, sessionId: {}", jsonMessage, sessionId); try { final String messageId = jsonMessage.get("id").getAsString(); switch (messageId) { case "PROCESS_SDP_OFFER": // Start: Create user session and process SDP Offer handleProcessSdpOffer(session, jsonMessage); break; case "ADD_ICE_CANDIDATE": handleAddIceCandidate(session, jsonMessage); break; case "STOP": handleStop(session, jsonMessage); break; case "ERROR": handleError(session, jsonMessage); break; default: // Ignore the message log.warn("[Handler::handleTextMessage] Skip, invalid message, id: {}", messageId); break; } } catch (Throwable ex) { log.error("[Handler::handleTextMessage] Exception: {}, sessionId: {}", ex, sessionId); sendError(session, "[Kurento] Exception: " + ex.getMessage()); } }
Example 12
Source File: Handler.java From kurento-tutorial-java with Apache License 2.0 | 5 votes |
private void initWebRtcEndpoint(final WebSocketSession session, final WebRtcEndpoint webRtcEp, String sdpOffer) { initBaseEventListeners(session, webRtcEp, "WebRtcEndpoint"); initWebRtcEventListeners(session, webRtcEp); final String sessionId = session.getId(); final String name = "user" + sessionId + "_webrtcendpoint"; webRtcEp.setName(name); /* OPTIONAL: Force usage of an Application-specific STUN server. Usually this is configured globally in KMS WebRTC settings file: /etc/kurento/modules/kurento/WebRtcEndpoint.conf.ini But it can also be configured per-application, as shown: log.info("[Handler::initWebRtcEndpoint] Using STUN server: 193.147.51.12:3478"); webRtcEp.setStunServerAddress("193.147.51.12"); webRtcEp.setStunServerPort(3478); */ // Continue the SDP Negotiation: Generate an SDP Answer final String sdpAnswer = webRtcEp.processOffer(sdpOffer); log.info("[Handler::initWebRtcEndpoint] name: {}, SDP Offer from browser to KMS:\n{}", name, sdpOffer); log.info("[Handler::initWebRtcEndpoint] name: {}, SDP Answer from KMS to browser:\n{}", name, sdpAnswer); JsonObject message = new JsonObject(); message.addProperty("id", "PROCESS_SDP_ANSWER"); message.addProperty("sdpAnswer", sdpAnswer); sendMessage(session, message.toString()); }
Example 13
Source File: Handler.java From kurento-tutorial-java with Apache License 2.0 | 5 votes |
@Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class); String sessionId = session.getId(); log.debug("[Handler::handleTextMessage] {}, sessionId: {}", jsonMessage, sessionId); try { String messageId = jsonMessage.get("id").getAsString(); switch (messageId) { case "PROCESS_SDP_OFFER": handleProcessSdpOffer(session, jsonMessage); break; case "ADD_ICE_CANDIDATE": handleAddIceCandidate(session, jsonMessage); break; case "STOP": handleStop(session, jsonMessage); break; default: sendError(session, "Invalid message, id: " + messageId); break; } } catch (Throwable ex) { log.error("[Handler::handleTextMessage] Exception: {}, sessionId: {}", ex, sessionId); sendError(session, "Exception: " + ex.getMessage()); } }
Example 14
Source File: UserSession.java From kurento-tutorial-java with Apache License 2.0 | 4 votes |
public UserSession(WebSocketSession session) { this.id = session.getId(); }
Example 15
Source File: OfframpWebSocketHandler.java From data-highway with Apache License 2.0 | 4 votes |
@Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessionId = session.getId(); Map<String, Object> attributes = session.getAttributes(); version = (String) attributes.get(VERSION); roadName = (String) attributes.get(ROAD_NAME); streamName = (String) attributes.get(STREAM_NAME); DefaultOffset defaultOffset = (DefaultOffset) attributes.get(DEFAULT_OFFSET); @SuppressWarnings("unchecked") Set<Sensitivity> grants = (Set<Sensitivity>) attributes.get(GRANTS); Authentication authentication = (Authentication) session.getPrincipal(); RoadConsumer consumer; metrics = metricsFactory.create(roadName, streamName); try { authorisation.checkAuthorisation(authentication, roadName, grants); consumer = consumerFactory.create(roadName, streamName, defaultOffset); MessageFunction messageFunction = messageFunctionFactory.create(roadName, grants); EventSender sender = bytes -> sendEvent(session, bytes); service = serviceFactory.create(version, consumer, messageFunction, sender, metrics); } catch (UnknownRoadException e) { metrics.markRoadNotFound(); session.close(); throw e; } Scheduler scheduler = Schedulers.newSingle( String.format("offramp[v%s,%s.%s:%s]", version, roadName, streamName, sessionId)); metrics.incrementActiveConnections(); Mono<Void> mono = Mono .fromRunnable(service) .subscribeOn(scheduler) .doOnError(t -> true, t -> { log.error("Road: {}, stream: {}, sessionId: {} - Error in OfframpService", roadName, streamName, sessionId, t); }) .doOnSuccess(s -> { log.info("Road: {}, stream: {}, sessionId: {} - OfframpService Completed", roadName, streamName, sessionId); }) .doOnTerminate(() -> { disposables.dispose(); metrics.decrementActiveConnections(); }).then(); disposables.add(() -> close(service)); disposables.add(() -> close(consumer)); disposables.add(() -> close(() -> session.close(SERVER_ERROR))); disposables.add(scheduler); disposables.add(mono.subscribe()); log.info("Road: {}, stream: {}, sessionId: {} - Connection established with defaultOffset: {}", roadName, streamName, sessionId, defaultOffset); metrics.markConnectionEstablished(); }
Example 16
Source File: Handler.java From kurento-tutorial-java with Apache License 2.0 | 4 votes |
private void handleProcessSdpOffer(final WebSocketSession session, JsonObject jsonMessage) { // ---- Session handling String sessionId = session.getId(); log.info("[Handler::handleStart] User count: {}", users.size()); log.info("[Handler::handleStart] New user: {}", sessionId); final UserSession user = new UserSession(); users.put(session.getId(), user); // ---- Media pipeline log.info("[Handler::handleStart] Create Media Pipeline"); final MediaPipeline pipeline = kurento.createMediaPipeline(); user.setMediaPipeline(pipeline); final WebRtcEndpoint webRtcEp = new WebRtcEndpoint.Builder(pipeline).build(); user.setWebRtcEndpoint(webRtcEp); Boolean useSrtp = jsonMessage.get("useSrtp").getAsBoolean(); final RtpEndpoint rtpEp = makeRtpEndpoint(pipeline, useSrtp); user.setRtpEndpoint(rtpEp); // ---- Endpoint configuration rtpEp.connect(webRtcEp); String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); initWebRtcEndpoint(session, webRtcEp, sdpOffer); startWebRtcEndpoint(webRtcEp); Boolean useComedia = jsonMessage.get("useComedia").getAsBoolean(); startRtpEndpoint(session, rtpEp, useComedia, useSrtp); // ---- Debug // String pipelineDot = pipeline.getGstreamerDot(); // try (PrintWriter out = new PrintWriter("pipeline.dot")) { // out.println(pipelineDot); // } catch (IOException ex) { // log.error("[Handler::start] Exception: {}", ex.getMessage()); // } }
Example 17
Source File: StompSubProtocolHandler.java From spring4-understanding with Apache License 2.0 | 4 votes |
/** * Handle STOMP messages going back out to WebSocket clients. */ @Override @SuppressWarnings("unchecked") public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message.getPayload() instanceof byte[])) { logger.error("Expected byte[] payload. Ignoring " + message + "."); return; } StompHeaderAccessor stompAccessor = getStompHeaderAccessor(message); StompCommand command = stompAccessor.getCommand(); if (StompCommand.MESSAGE.equals(command)) { if (stompAccessor.getSubscriptionId() == null) { logger.warn("No STOMP \"subscription\" header in " + message); } String origDestination = stompAccessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); if (origDestination != null) { stompAccessor = toMutableAccessor(stompAccessor, message); stompAccessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); stompAccessor.setDestination(origDestination); } } else if (StompCommand.CONNECTED.equals(command)) { this.stats.incrementConnectedCount(); stompAccessor = afterStompSessionConnected(message, stompAccessor, session); if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) { try { SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes()); SimpAttributesContextHolder.setAttributes(simpAttributes); Principal user = session.getPrincipal(); publishEvent(new SessionConnectedEvent(this, (Message<byte[]>) message, user)); } finally { SimpAttributesContextHolder.resetAttributes(); } } } byte[] payload = (byte[]) message.getPayload(); if (StompCommand.ERROR.equals(command) && getErrorHandler() != null) { Message<byte[]> errorMessage = getErrorHandler().handleErrorMessageToClient((Message<byte[]>) message); stompAccessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class); Assert.notNull(stompAccessor, "Expected STOMP headers"); payload = errorMessage.getPayload(); } sendToClient(session, stompAccessor, payload); }
Example 18
Source File: StompSubProtocolHandler.java From java-technology-stack with MIT License | 4 votes |
/** * Handle STOMP messages going back out to WebSocket clients. */ @Override @SuppressWarnings("unchecked") public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message.getPayload() instanceof byte[])) { if (logger.isErrorEnabled()) { logger.error("Expected byte[] payload. Ignoring " + message + "."); } return; } StompHeaderAccessor accessor = getStompHeaderAccessor(message); StompCommand command = accessor.getCommand(); if (StompCommand.MESSAGE.equals(command)) { if (accessor.getSubscriptionId() == null && logger.isWarnEnabled()) { logger.warn("No STOMP \"subscription\" header in " + message); } String origDestination = accessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); if (origDestination != null) { accessor = toMutableAccessor(accessor, message); accessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); accessor.setDestination(origDestination); } } else if (StompCommand.CONNECTED.equals(command)) { this.stats.incrementConnectedCount(); accessor = afterStompSessionConnected(message, accessor, session); if (this.eventPublisher != null) { try { SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes()); SimpAttributesContextHolder.setAttributes(simpAttributes); Principal user = getUser(session); publishEvent(this.eventPublisher, new SessionConnectedEvent(this, (Message<byte[]>) message, user)); } finally { SimpAttributesContextHolder.resetAttributes(); } } } byte[] payload = (byte[]) message.getPayload(); if (StompCommand.ERROR.equals(command) && getErrorHandler() != null) { Message<byte[]> errorMessage = getErrorHandler().handleErrorMessageToClient((Message<byte[]>) message); if (errorMessage != null) { accessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class); Assert.state(accessor != null, "No StompHeaderAccessor"); payload = errorMessage.getPayload(); } } sendToClient(session, accessor, payload); }
Example 19
Source File: StompSubProtocolHandler.java From spring-analysis-note with MIT License | 4 votes |
/** * Handle STOMP messages going back out to WebSocket clients. */ @Override @SuppressWarnings("unchecked") public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message.getPayload() instanceof byte[])) { if (logger.isErrorEnabled()) { logger.error("Expected byte[] payload. Ignoring " + message + "."); } return; } StompHeaderAccessor accessor = getStompHeaderAccessor(message); StompCommand command = accessor.getCommand(); if (StompCommand.MESSAGE.equals(command)) { if (accessor.getSubscriptionId() == null && logger.isWarnEnabled()) { logger.warn("No STOMP \"subscription\" header in " + message); } String origDestination = accessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); if (origDestination != null) { accessor = toMutableAccessor(accessor, message); accessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); accessor.setDestination(origDestination); } } else if (StompCommand.CONNECTED.equals(command)) { this.stats.incrementConnectedCount(); accessor = afterStompSessionConnected(message, accessor, session); if (this.eventPublisher != null) { try { SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes()); SimpAttributesContextHolder.setAttributes(simpAttributes); Principal user = getUser(session); publishEvent(this.eventPublisher, new SessionConnectedEvent(this, (Message<byte[]>) message, user)); } finally { SimpAttributesContextHolder.resetAttributes(); } } } byte[] payload = (byte[]) message.getPayload(); if (StompCommand.ERROR.equals(command) && getErrorHandler() != null) { Message<byte[]> errorMessage = getErrorHandler().handleErrorMessageToClient((Message<byte[]>) message); if (errorMessage != null) { accessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class); Assert.state(accessor != null, "No StompHeaderAccessor"); payload = errorMessage.getPayload(); } } sendToClient(session, accessor, payload); }
Example 20
Source File: Handler.java From kurento-tutorial-java with Apache License 2.0 | 2 votes |
private void handleProcessSdpOffer(final WebSocketSession session, JsonObject jsonMessage) { // ---- Session handling final String sessionId = session.getId(); log.info("[Handler::handleStart] User count: {}", users.size()); log.info("[Handler::handleStart] New user, id: {}", sessionId); final UserSession user = new UserSession(); users.put(sessionId, user); // ---- Media pipeline log.info("[Handler::handleStart] Create Media Pipeline"); final MediaPipeline pipeline = kurento.createMediaPipeline(); user.setMediaPipeline(pipeline); final WebRtcEndpoint webRtcEp = new WebRtcEndpoint.Builder(pipeline).build(); user.setWebRtcEndpoint(webRtcEp); webRtcEp.connect(webRtcEp); // ---- Endpoint configuration String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); initWebRtcEndpoint(session, webRtcEp, sdpOffer); log.info("[Handler::handleStart] New WebRtcEndpoint: {}", webRtcEp.getName()); // ---- Endpoint startup startWebRtcEndpoint(webRtcEp); // ---- Debug // final String pipelineDot = pipeline.getGstreamerDot(); // try (PrintWriter out = new PrintWriter("pipeline.dot")) { // out.println(pipelineDot); // } catch (IOException ex) { // log.error("[Handler::start] Exception: {}", ex.getMessage()); // } }