javax.websocket.Session Java Examples
The following examples show how to use
javax.websocket.Session.
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: RoomEndpoint.java From sample-room-java with Apache License 2.0 | 9 votes |
@Timed(name = "websocket_onOpen_timer", reusable = true, tags = "label=websocket") @Counted(name = "websocket_onOpen_count", monotonic = true, reusable = true, tags = "label=websocket") @Metered(name = "websocket_onOpen_meter", reusable = true, tags = "label=websocket") @OnOpen public void onOpen(Session session, EndpointConfig ec) { Log.log(Level.FINE, this, "A new connection has been made to the room."); // All we have to do in onOpen is send the acknowledgement sendMessage(session, Message.ACK_MSG); }
Example #2
Source File: WebsocketBasicAuthTestCase.java From quarkus-http with Apache License 2.0 | 7 votes |
@Override public void onOpen(Session session, EndpointConfig config) { this.session = session; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } session.addMessageHandler(new MessageHandler.Whole<String>() { @Override public void onMessage(String message) { responses.add(message); } }); }
Example #3
Source File: WebSocketMessagingBus.java From triplea with GNU General Public License v3.0 | 6 votes |
@SuppressWarnings("unchecked") <T extends WebSocketMessage> void onMessage( final Session session, final MessageEnvelope envelope) { determineMatchingMessageType(envelope) .ifPresent( messageType -> { final T payload = (T) envelope.getPayload(messageType.getPayloadType()); getListenersForMessageTypeId(envelope.getMessageTypeId()) .map(messageListener -> (MessageListener<T>) messageListener) .forEach( messageListener -> messageListener.listener.accept( WebSocketMessageContext.<T>builder() .messagingBus(this) .senderSession(session) .message(payload) .build())); }); }
Example #4
Source File: LearningWebsocketServer.java From lams with GNU General Public License v2.0 | 6 votes |
/** * When user leaves the activity. */ @OnClose public void unregisterUser(Session websocket, CloseReason reason) { Long toolSessionId = Long .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0)); LearningWebsocketServer.websockets.get(toolSessionId).remove(websocket); if (LearningWebsocketServer.log.isDebugEnabled()) { // If there was something wrong with the connection, put it into logs. LearningWebsocketServer.log.debug("User " + websocket.getUserPrincipal().getName() + " left Mindmap with Tool Session ID: " + toolSessionId + (!(reason.getCloseCode().equals(CloseCodes.GOING_AWAY) || reason.getCloseCode().equals(CloseCodes.NORMAL_CLOSURE)) ? ". Abnormal close. Code: " + reason.getCloseCode() + ". Reason: " + reason.getReasonPhrase() : "")); } }
Example #5
Source File: Chatters.java From triplea with GNU General Public License v3.0 | 6 votes |
private void disconnectSession( final Collection<Session> sessions, final String disconnectMessage) { // Do session disconnects as its own step to avoid concurrent modification. sessions.forEach( session -> { try { session.close( new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, disconnectMessage)); } catch (final IOException e) { log.warn( "While closing session, " + "session close threw an exception, session is left open? {}", session.isOpen(), e); } }); }
Example #6
Source File: DrawboardEndpoint.java From tomcatsrc with Apache License 2.0 | 6 votes |
@Override public void onClose(Session session, CloseReason closeReason) { Room room = getRoom(false); if (room != null) { room.invokeAndWait(new Runnable() { @Override public void run() { try { // Player can be null if it couldn't enter the room if (player != null) { // Remove this player from the room. player.removeFromRoom(); // Set player to null to prevent NPEs when onMessage events // are processed (from other threads) after onClose has been // called from different thread which closed the Websocket session. player = null; } } catch (RuntimeException ex) { log.error("Unexpected exception: " + ex.toString(), ex); } } }); } }
Example #7
Source File: ServerWebSocketContainer.java From quarkus-http with Apache License 2.0 | 6 votes |
public Session connectToServer(Class<?> aClass, WebsocketConnectionBuilder connectionBuilder) throws DeploymentException, IOException { if (closed) { throw new ClosedChannelException(); } ConfiguredClientEndpoint config = getClientEndpoint(aClass, true); if (config == null) { throw JsrWebSocketMessages.MESSAGES.notAValidClientEndpointType(aClass); } try { AnnotatedEndpointFactory factory = config.getFactory(); InstanceHandle<?> instance = config.getInstanceFactory().createInstance(); return connectToServerInternal(factory.createInstance(instance), config, connectionBuilder); } catch (InstantiationException e) { throw new RuntimeException(e); } }
Example #8
Source File: EchoAsyncAnnotation.java From Tomcat8-Source-Read with MIT License | 6 votes |
@OnMessage public void echoTextMessage(Session session, String msg, boolean last) { if (sb == null) { sb = new StringBuilder(); } sb.append(msg); if (last) { // Before we send the next message, have to wait for the previous // message to complete try { f.get(); } catch (InterruptedException | ExecutionException e) { // Let the container deal with it throw new RuntimeException(e); } f = session.getAsyncRemote().sendText(sb.toString()); sb = null; } }
Example #9
Source File: CommandWebsocketServer.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Removes Learner websocket from the collection. */ @OnClose public void unregisterUser(Session session, CloseReason reason) { String login = session.getUserPrincipal().getName(); if (login == null) { return; } Long lessonId = Long.valueOf(session.getRequestParameterMap().get(AttributeNames.PARAM_LESSON_ID).get(0)); Map<String, Session> lessonWebsockets = CommandWebsocketServer.websockets.get(lessonId); if (lessonWebsockets == null) { return; } lessonWebsockets.remove(login); }
Example #10
Source File: CollaborativeWebSocketModuleImpl.java From eplmp with Eclipse Public License 1.0 | 5 votes |
private void onCollaborativeInviteMessage(String sender, Session session, WebSocketMessage webSocketMessage) { String invitedUser = webSocketMessage.getString("remoteUser"); JsonObject broadcastMessage = webSocketMessage.getJsonObject("broadcastMessage"); String context = broadcastMessage.getString("context"); String url = broadcastMessage.getString("url"); CollaborativeRoom room = CollaborativeRoom.getByKeyName(webSocketMessage.getString("key")); if (webSocketSessionsManager.isAllowedToReachUser(sender, invitedUser)) { if (room.getMasterName().equals(sender) && room.findUserSession(invitedUser) == null) { // the master sent the invitation // the user is not already in the room if (!room.getPendingUsers().contains(invitedUser)) { // the user is not yet in the pending list, add him. room.addPendingUser(invitedUser); } String invite = "/invite " + url + "/room/" + room.getKey(); JsonObjectBuilder b = Json.createObjectBuilder() .add("type", CHAT_MESSAGE) .add("remoteUser", sender) .add("sender", sender) .add("message", invite) .add("context", context); WebSocketMessage message = new WebSocketMessage(b.build()); webSocketSessionsManager.broadcast(invitedUser, message); broadcastNewContext(room); } } }
Example #11
Source File: Room.java From eplmp with Eclipse Public License 1.0 | 5 votes |
public static void removeUserFromAllRoom(String callerLogin) { Set<Map.Entry<String, Room>> roomsEntries = new HashSet<>(DB.entrySet()); for (Map.Entry<String, Room> entry : roomsEntries) { Session session = entry.getValue().getSessionForUserLogin(callerLogin); if (session != null) { entry.getValue().removeSession(session); } } }
Example #12
Source File: MockServerContainer.java From spring-analysis-note with MIT License | 5 votes |
@Override public Session connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path) throws DeploymentException, IOException { throw new UnsupportedOperationException( "MockServerContainer does not support connectToServer(Class, ClientEndpointConfig, URI)"); }
Example #13
Source File: WebSocketUtil.java From OneBlog with GNU General Public License v3.0 | 5 votes |
/** * 群发 * * @param message * 消息内容 * @param sessionSet * 客户端session列表 * @throws IOException */ private static void broadcast(String message, Set<Session> sessionSet) { if (CollectionUtils.isEmpty(sessionSet)) { return; } // 多线程群发 for (Session entry : sessionSet) { if (null != entry && entry.isOpen()) { sendMessage(message, entry); } else { sessionSet.remove(entry); } } }
Example #14
Source File: RoomEndpoint.java From sample-room-java with Apache License 2.0 | 5 votes |
@Timed(name = "websocket_onClose_timer", reusable = true, tags = "label=websocket") @Counted(name = "websocket_onClose_count", monotonic = true, reusable = true, tags = "label=websocket") @Metered(name = "websocket_onClose_meter", reusable = true, tags = "label=websocket") @OnClose public void onClose(Session session, CloseReason r) { Log.log(Level.FINE, this, "A connection to the room has been closed with reason " + r); }
Example #15
Source File: TomcatWebSocketEndpoint.java From MyBlog with Apache License 2.0 | 5 votes |
public void sendMessage(Session session, String message) { try { session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId())); } catch (IOException e) { log.error("发送消息出错:{}", e.getMessage()); e.printStackTrace(); } }
Example #16
Source File: Chatters.java From triplea with GNU General Public License v3.0 | 5 votes |
/** * Disconnects all sessions belonging to a given player identified by name. A disconnected session * is closed, the closure will trigger a notification on the client of the disconnected player. * * @param userName The name of the player whose sessions will be disconnected. * @param disconnectMessage Message that will be displayed to the disconnected player. * @return True if any sessions were disconnected, false if none (indicating player was no longer * in chat). */ public boolean disconnectPlayerByName(final UserName userName, final String disconnectMessage) { final Set<Session> sessions = participants.values().stream() .filter( chatterSession -> chatterSession.getChatParticipant().getUserName().equals(userName)) .map(ChatterSession::getSession) .collect(Collectors.toSet()); disconnectSession(sessions, disconnectMessage); return !sessions.isEmpty(); }
Example #17
Source File: WebSocket.java From jeecg-boot with Apache License 2.0 | 5 votes |
public void sendMoreMessage(String[] userIds, String message) { for(String userId:userIds) { Session session = sessionPool.get(userId); if (session != null&&session.isOpen()) { try { log.info("【websocket消息】 单点消息:"+message); session.getAsyncRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } }
Example #18
Source File: LearningWebsocketServer.java From lams with GNU General Public License v2.0 | 5 votes |
/** * The scribe has submitted a report. */ private static void submitReport(ObjectNode requestJSON, Session websocket) { Long toolSessionId = Long .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0)); String userName = websocket.getUserPrincipal().getName(); LearningWebsocketServer.getScribeService().submitReport(toolSessionId, userName, requestJSON); }
Example #19
Source File: WsHelperImpl.java From tephra with MIT License | 5 votes |
@Override public void open(Session session) { String sid = getSessionId(session); sessions.put(sid, session); ips.put(sid, context.getThreadLocal(IP)); if (port == 0) port = context.getThreadLocal(PORT); if (logger.isDebugEnable()) logger.debug("新的WebSocket连接[{}:{}:{}]。", port, ips.get(sid), sid); }
Example #20
Source File: TestPojoEndpointBase.java From tomcatsrc with Apache License 2.0 | 5 votes |
@OnOpen public void onOpen(@SuppressWarnings("unused") Session session, EndpointConfig config) { if (config == null) { throw new RuntimeException(); } }
Example #21
Source File: WebPodsClient.java From diirt with MIT License | 5 votes |
@OnOpen public void onOpen(Session session) { synchronized(lock) { this.session = session; connected = true; disconnectReason = null; } for (Map.Entry<Integer, WebPodsChannel> entrySet : channels.entrySet()) { WebPodsChannel channel = entrySet.getValue(); subscribeChannel(channel); } }
Example #22
Source File: GuacamoleWebSocketTunnelEndpoint.java From guacamole-client with Apache License 2.0 | 5 votes |
@Override @OnClose public void onClose(Session session, CloseReason closeReason) { try { if (tunnel != null) tunnel.close(); } catch (GuacamoleException e) { logger.debug("Unable to close WebSocket tunnel.", e); } }
Example #23
Source File: CodingClient.java From quarkus with Apache License 2.0 | 5 votes |
@OnOpen public void onOpen(Session session) { sessions.add(session); Dto data = new Dto(); data.setContent("initial data"); session.getAsyncRemote().sendObject(data); }
Example #24
Source File: ProgramaticLazyEndpointTest.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public void onOpen(Session session, EndpointConfig config) { this.session = session; session.getAsyncRemote().sendText("Stuart"); session.addMessageHandler(new MessageHandler.Whole<String>() { @Override public void onMessage(String message) { responses.add(message); } }); }
Example #25
Source File: WebSocketClientEndpoint.java From rogue-cloud with Apache License 2.0 | 5 votes |
@OnClose public void close(Session session) { System.out.println("close."); // If the websocket was added as a managed resource, it can now be removed. ResourceLifecycleUtil.getInstance().removeSession(ServerWsClientUtil.convertSessionToManagedResource(session)); }
Example #26
Source File: NotificationsEndpoint.java From pnc with Apache License 2.0 | 5 votes |
private void respondWithErrorMessage(String errorMessage, Response.Status status, Session session, Exception e) { String statusCode = Integer.toString(status.getStatusCode()); String error = JsonOutputConverterMapper.apply(new ErrorResponse(statusCode, errorMessage)); if (e != null) { logger.warn(errorMessage, e); } else { logger.warn(errorMessage); } session.getAsyncRemote().sendText(error); }
Example #27
Source File: StandardWebSocketHandlerAdapter.java From java-technology-stack with MIT License | 5 votes |
@Override public void onClose(Session session, CloseReason reason) { if (this.delegateSession != null) { int code = reason.getCloseCode().getCode(); this.delegateSession.handleClose(new CloseStatus(code, reason.getReasonPhrase())); } }
Example #28
Source File: PresenceWebsocketServer.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Checks which Learners * * @throws IOException * @throws JsonProcessingException */ private ArrayNode getRosterJSON() throws JsonProcessingException, IOException { Set<String> localActiveUsers = new TreeSet<>(); Set<Session> lessonWebsockets = PresenceWebsocketServer.websockets.get(lessonId); // find out who is active locally for (Session websocket : lessonWebsockets) { localActiveUsers.add((String) websocket.getUserProperties().get(PARAM_NICKNAME)); } // is it time to sync with the DB yet? long currentTime = System.currentTimeMillis(); if ((currentTime - lastDBCheckTime) > IPresenceChatService.PRESENCE_IDLE_TIMEOUT) { // store Learners active on this node PresenceWebsocketServer.getPresenceChatService().updateUserPresence(lessonId, localActiveUsers); // read active Learners from all nodes List<PresenceChatUser> storedActiveUsers = PresenceWebsocketServer.getPresenceChatService() .getUsersActiveByLessonId(lessonId); // refresh current collection activeUsers.clear(); for (PresenceChatUser activeUser : storedActiveUsers) { activeUsers.add(activeUser.getNickname()); } lastDBCheckTime = currentTime; } else { // add users active on this node; no duplicates - it is a set, not a list activeUsers.addAll(localActiveUsers); } return JsonUtil.readArray(activeUsers); }
Example #29
Source File: FakeKubernetesWebSocketB.java From wildfly-camel with Apache License 2.0 | 5 votes |
@OnOpen public void onConnectionOpen(Session session) { try { String resource = TestUtils.getResourceValue(FakeKubernetesWebSocketB.class, "/event.json"); session.getBasicRemote().sendBinary(ByteBuffer.wrap(resource.getBytes())); } catch (IOException e) { throw new IllegalStateException("Unable to read resource: event.json", e); } }
Example #30
Source File: PojoEndpointBase.java From tomcatsrc with Apache License 2.0 | 5 votes |
private void handleOnOpenError(Session session, Throwable t) { // If really fatal - re-throw ExceptionUtils.handleThrowable(t); // Trigger the error handler and close the session onError(session, t); try { session.close(); } catch (IOException ioe) { log.warn(sm.getString("pojoEndpointBase.closeSessionFail"), ioe); } }