@OnOpen public void onOpen(Session session, @PathParam("uuid") String uuid) { UUID key = UUID.fromString(uuid); peers.put(key, session); JsonArrayBuilder builder = Json.createArrayBuilder(); for (StatusEventType statusEventType : StatusEventType.values()) { JsonObjectBuilder object = Json.createObjectBuilder(); builder.add(object.add(statusEventType.name(), statusEventType.getMessage()).build()); } RemoteEndpoint.Async asyncRemote = session.getAsyncRemote(); asyncRemote.sendText(builder.build().toString()); // Send pending messages List<String> messages = messageBuffer.remove(key); if (messages != null) { messages.forEach(asyncRemote::sendText); } }
@OnOpen public void onOpen(Session session) throws NamingException { logger.info("Open session:" + session.getId()); ManagedExecutorService mes = doLookup("java:comp/DefaultManagedExecutorService"); final Session s = session; mes.execute(new Runnable() { @Override public void run() { try { for (int i = 0; i < 3; i++) { sleep(10000); s.getBasicRemote().sendText("Message from server"); } } catch (InterruptedException | IOException e) { logger.log(SEVERE, "connection error", e); } } }); }
/** * Registeres the Learner for processing. */ @OnOpen public void registerUser(Session websocket) throws JSONException, IOException { Long toolContentID = Long .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_CONTENT_ID).get(0)); Set<Session> toolContentWebsockets = websockets.get(toolContentID); if (toolContentWebsockets == null) { toolContentWebsockets = ConcurrentHashMap.newKeySet(); websockets.put(toolContentID, toolContentWebsockets); } toolContentWebsockets.add(websocket); if (log.isDebugEnabled()) { log.debug("User " + websocket.getUserPrincipal().getName() + " entered Dokumaran with toolContentId: " + toolContentID); } }
/** * Registeres the Learner for processing. */ @OnOpen public void registerUser(Session websocket) throws JSONException, IOException { Long toolSessionId = Long .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0)); Set<Session> sessionWebsockets = websockets.get(toolSessionId); if (sessionWebsockets == null) { sessionWebsockets = ConcurrentHashMap.newKeySet(); websockets.put(toolSessionId, sessionWebsockets); } sessionWebsockets.add(websocket); if (log.isDebugEnabled()) { log.debug("User " + websocket.getUserPrincipal().getName() + " entered Leader Selection with toolSessionId: " + toolSessionId); } }
/** * Registeres the Learner for processing by SendWorker. */ @OnOpen public void registerUser(Session session) throws IOException { Long lessonId = Long.valueOf(session.getRequestParameterMap().get(AttributeNames.PARAM_LESSON_ID).get(0)); Set<Websocket> sessionWebsockets = PresenceWebsocketServer.websockets.get(lessonId); if (sessionWebsockets == null) { sessionWebsockets = ConcurrentHashMap.newKeySet(); PresenceWebsocketServer.websockets.put(lessonId, sessionWebsockets); } Websocket websocket = new Websocket(session); sessionWebsockets.add(websocket); Roster roster = PresenceWebsocketServer.rosters.get(lessonId); if (roster == null) { boolean imEnabled = Boolean.valueOf(session.getRequestParameterMap().get("imEnabled").get(0)); // build a new roster object roster = new Roster(lessonId, imEnabled); PresenceWebsocketServer.rosters.put(lessonId, roster); } new Thread(() -> { try { // websocket communication bypasses standard HTTP filters, so Hibernate session needs to be initialised manually HibernateSessionManager.openSession(); SendWorker.send(lessonId, websocket.nickName); } finally { HibernateSessionManager.closeSession(); } }).start(); if (PresenceWebsocketServer.log.isDebugEnabled()) { PresenceWebsocketServer.log .debug("User " + websocket.nickName + " entered Presence Chat with lesson ID: " + lessonId); } }
/** * Registeres the Learner for processing by SendWorker. */ @OnOpen public void registerUser(Session session) throws IOException { Long toolSessionId = Long .valueOf(session.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0)); Set<Websocket> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId); if (sessionWebsockets == null) { sessionWebsockets = ConcurrentHashMap.newKeySet(); LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets); } final Set<Websocket> finalSessionWebsockets = sessionWebsockets; String userName = session.getUserPrincipal().getName(); new Thread(() -> { try { // websocket communication bypasses standard HTTP filters, so Hibernate session needs to be initialised manually HibernateSessionManager.openSession(); ChatUser chatUser = LearningWebsocketServer.getChatService().getUserByLoginNameAndSessionId(userName, toolSessionId); Websocket websocket = new Websocket(session, chatUser.getNickname(), chatUser.getUserId(), getPortraitId(chatUser.getUserId())); finalSessionWebsockets.add(websocket); // update the chat window immediatelly SendWorker.send(toolSessionId); if (LearningWebsocketServer.log.isDebugEnabled()) { LearningWebsocketServer.log .debug("User " + userName + " entered Chat with toolSessionId: " + toolSessionId); } } finally { HibernateSessionManager.closeSession(); } }).start(); }
/** * Registeres the Learner for processing by SendWorker. */ @OnOpen public void registerUser(Session websocket) throws JSONException, IOException { Long toolSessionId = Long .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0)); Set<Session> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId); if (sessionWebsockets == null) { sessionWebsockets = ConcurrentHashMap.newKeySet(); LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets); Map<Long, Map<Long, Boolean>> sessionCache = new TreeMap<>(); LearningWebsocketServer.cache.put(toolSessionId, sessionCache); } sessionWebsockets.add(websocket); if (LearningWebsocketServer.log.isDebugEnabled()) { LearningWebsocketServer.log.debug("User " + websocket.getUserPrincipal().getName() + " entered Scratchie with toolSessionId: " + toolSessionId); } }
/** * Registeres the Learner for processing by SendWorker. */ @OnOpen public void registerUser(Session websocket) throws JSONException, IOException { Long toolSessionId = Long .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0)); Set<Session> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId); if (sessionWebsockets == null) { sessionWebsockets = ConcurrentHashMap.newKeySet(); LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets); } sessionWebsockets.add(websocket); if (LearningWebsocketServer.log.isDebugEnabled()) { LearningWebsocketServer.log.debug("User " + websocket.getUserPrincipal().getName() + " entered Scribe with toolSessionId: " + toolSessionId); } new Thread(() -> { try { HibernateSessionManager.openSession(); SendWorker.send(toolSessionId, websocket); } catch (Exception e) { log.error("Error while sending messages", e); } finally { HibernateSessionManager.closeSession(); } }).start(); }
/** * 连接建立成功调用的方法-与前端JS代码对应 * * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(Session session, EndpointConfig config) { // 单个会话对象保存 this.session = session; webSocketSet.add(this); // 加入set中 this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName()); String uId = (String) httpSession.getAttribute("userid"); // 获取当前用户 String sessionId = httpSession.getId(); this.userid = uId + "|" + sessionId; if (!OnlineUserlist.contains(this.userid)) { OnlineUserlist.add(userid); // 将用户名加入在线列表 } routetabMap.put(userid, session); // 将用户名和session绑定到路由表 System.out.println(userid + " -> 已上线"); String message = getMessage(userid + " -> 已上线", "notice", OnlineUserlist); broadcast(message); // 广播 }
@OnOpen public void userConnectedCallback(@PathParam("user") String user, Session s) { if (USERS.contains(user)) { try { dupUserDetected = true; s.getBasicRemote().sendText("Username " + user + " has been taken. Retry with a different name"); s.close(); return; } catch (IOException ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex); } } this.s = s; s.getUserProperties().put("user", user); this.user = user; USERS.add(user); welcomeNewJoinee(); announceNewJoinee(); }
@OnOpen public void userConnectedCallback(@PathParam("user") String user, Session s) { if (USERS.contains(user)) { try { dupUserDetected = true; s.getBasicRemote().sendObject(new DuplicateUserNotification(user)); s.close(); return; } catch (Exception ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex); } } this.s = s; SESSIONS.add(s); s.getUserProperties().put("user", user); this.user = user; USERS.add(user); welcomeNewJoinee(); announceNewJoinee(); }
/**连接建立成功调用的方法*/ @OnOpen public void onOpen(Session session,EndpointConfig config){ HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName()); if(StorageUtil.init(httpSession).getLoginMemberId()!=ReturnUtil.NOT_LOGIN_CODE){ long userId = StorageUtil.init(httpSession).getLoginMemberId(); mapUS.put(userId,session); mapSU.put(session,userId); //上线通知由客户端自主发起 onlineCount++; //在线数加1 System.out.println("用户"+userId+"进入WebSocket!当前在线人数为" + onlineCount); getUserKey(userId); }else{ try { session.close(); System.out.println("未获取到用户信息,关闭WebSocket!"); } catch (IOException e) { System.out.println("关闭WebSocket失败!"); } } }
/** * Open a socket connection to a client from the web server * * @param session The session that just opened */ @OnOpen public void openSocket(@PathParam(RT_COMPUTE_ENDPOINT_PARAM) ConnectionType type, Session session) { session.setMaxIdleTimeout(0); String sessionId = session.getId(); if (type == ConnectionType.SUBSCRIBER) { LOG.info("Got a new subscriber connection request with ID {}. Saving session", sessionId); // cleanup sessions Set<Session> closedSessions = Sets.newHashSet(); for (Session existingSession : sessions) { if (!existingSession.isOpen()) { closedSessions.add(existingSession); } } sessions.removeAll(closedSessions); sessions.add(session); LOG.info("Active sessions {}. Collecting {} sessions", sessions.size(), closedSessions.size()); } else { LOG.info("Got a new publisher connection request with ID {}", sessionId); } }
@OnOpen public void onOpen(Session session,@PathParam("username") String username) { try{ client.add(session); user.put(URLEncoder.encode(username, "UTF-8"),URLEncoder.encode(username, "UTF-8")); JSONObject jo = new JSONObject(); JSONArray ja = new JSONArray(); //获得在线用户列表 Set<String> key = user.keySet(); for (String u : key) { ja.add(u); } jo.put("onlineUser", ja); session.getBasicRemote().sendText(jo.toString()); }catch(Exception e){ //do nothing } }
@OnOpen public void onOpen(Session session, @PathParam("uuid") String uuid) { UUID key = UUID.fromString(uuid); peers.put(key, session); JsonArrayBuilder builder = Json.createArrayBuilder(); for (StatusMessage statusMessage : StatusMessage.values()) { JsonObjectBuilder object = Json.createObjectBuilder(); builder.add(object.add(statusMessage.name(), statusMessage.getMessage()).build()); } RemoteEndpoint.Async asyncRemote = session.getAsyncRemote(); asyncRemote.sendText(builder.build().toString()); // Send pending messages List<String> messages = messageBuffer.remove(key); if (messages != null) { messages.forEach(asyncRemote::sendText); } }
@OnOpen public void onOpen(Session userSession) throws InterruptedException { String clientIp = ((TyrusSession)userSession).getRemoteAddr(); InetAddress identity; try { identity = InetAddress.getByName(clientIp); } catch (UnknownHostException e) { try { userSession.close(); } catch (IOException er) { return; } return; } WebsocketPeer.WebsocketSession session = localOpenSessions.putOpenSession(identity, userSession); Send<Bytestring> receiver = listener.newSession(session); receiveMap.put(userSession, receiver); }
@OnOpen public void onOpen(final Session session) { LOGGER.debug("Socket opened for session {}", session.getId()); // Endpoint setup this.session = session; reference = createReference(); // Session setup final String watcherId = getRequestParam("watcherId"); session.getUserProperties().put(REFERENCE_USER_PROP, reference); session.getUserProperties().put(WATCHER_ID_USER_PROP, watcherId); // FIXME Setting timeout with Jetty implementation doesn't work // session.setMaxIdleTimeout(TimeUnit.MILLISECONDS.toSeconds(20)); // Refresh watcher list to all sessions final List<Session> sessions = findSessionsWithSameReference(); final Set<String> allWatcherIds = getAllWatcherIds(sessions); sessions.forEach(someSession -> sendWatchersToSession(someSession, allWatcherIds)); }
/** * WebSocket session opened event handler. * * @param session - Session that has been opened */ @OnOpen public void open(Session session) { this.session = session; System.out.println("Session opened with ID: " + session.getId()); BallotBox ballotBox = BallotBox.getInstance(); ballotBox.addObserver(this); session.getUserProperties().put("ballotbox", ballotBox); try { notify(ballotBox); } catch (IOException | EncodeException e) { e.printStackTrace(); } }
/** * Connection opened by a client. * * @param session the WebSocket session for the connection. * @param conf the Endpoint configuration. */ @OnOpen public void onOpen(Session session, EndpointConfig conf) { log.debug("WebSocket new session: {}", session.getId()); this.isOpen = true; // // Initialization and Topology Service registration // this.socketSession = session; ITopologyService topologyService = WebSocketManager.topologyService; topologyService.addListener(this, true); // Start the thread start(); }
@OnOpen public void onOpen(Session websocketSession, EndpointConfig config) { LOGGER.debug("WebSocket open"); try { this.websocketSession = websocketSession; ServletContext servletContext = servletContexts.get(websocketSession.getContainer()); if (servletContext == null) { servletContext = defaultServletContext; } BimServer bimServer = (BimServer) servletContext.getAttribute("bimserver"); streamer = new Streamer(this, bimServer); streamer.onOpen(); } catch (Throwable t) { LOGGER.error("", t); } }
@OnOpen public void processOnOpen(Session session) { System.out.println("open connection id: " + session.getId()); File dir = new File("uploads"); if (!dir.exists()) { try { Files.createDirectory(dir.toPath()); } catch (IOException e) { e.printStackTrace(); } } this.session = session; this.storage = dir.toPath(); }
@OnOpen public void onOpen(Session session, EndpointConfig config) { try { this.request = (HttpServletRequest) config.getUserProperties().get("httpRequest"); this.response = (HttpServletResponse) config.getUserProperties().get("httpResponse"); this.session = (HttpSession) config.getUserProperties().get("httpSession"); Request _request = (Request) GenericReflection.NoThrow.getValue(Core.requestField, this.request); _request.setContext((Context) config.getUserProperties().get("context")); session.setMaxBinaryMessageBufferSize(JRenderConfig.Server.Request.Websocket.maxBinaryMessageSize); session.setMaxTextMessageBufferSize(JRenderConfig.Server.Request.Websocket.maxTextMessageSize); session.setMaxIdleTimeout(JRenderConfig.Server.Request.Websocket.maxIdleTimeout); } catch (Exception ex) { ex.printStackTrace(); } }
@OnOpen public void open(Session session) { System.out.printf("%s.open() called session=%s\n", getClass().getSimpleName(), session ); // This is a work around System.out.printf(" sampleSingleton = %s *BEFORE*\n", sampleSingleton ); if ( sampleSingleton == null) { // Look up the object Context initialContext = null; try { initialContext = new InitialContext(); Object obj = initialContext.lookup("java:global/mywebapp/SampleSingleton"); System.out.printf(" obj=%s\n", obj); sampleSingleton = (SampleSingleton)obj; } catch (NamingException e) { e.printStackTrace(); } } System.out.printf(" sampleSingleton = %s *AFTER*\n", sampleSingleton ); }
@OnOpen public void openRemoteConnection( final Session session) { System.out.printf("%s.openRemoteConnection( session = [%s], ", getClass().getSimpleName(), session); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { System.out.printf("%s.run( session = [%s], %s\n", getClass().getSimpleName(), session, price); session.getBasicRemote().sendText( "PRICE = " + price); synchronized (lock) { if (Math.random() < 0.5) { price = price.subtract(unitPrice); } else { price = price.add(unitPrice); } } } catch (IOException e) { e.printStackTrace(System.err); } } }, 500, 500, MILLISECONDS); }
/** * Callback when receiving opened connection from client side * * @param session the client {@link Session} * @param config the associated {@link EndpointConfig} to the new connection * @param executionId the execution identifier from the {@link ServerEndpoint} path */ @OnOpen public void openConnection(Session session, EndpointConfig config, @PathParam("execution-id") long executionId) { if (LOG.isDebugEnabled()) { LOG.debug("Session " + session.getId() + " opened connection to execution " + executionId); } mainLock.lock(); try { sessions.put(session.getId(), session); Set<String> registeredSessions = executions.get(executionId); if (registeredSessions == null) { registeredSessions = new HashSet<>(); } registeredSessions.add(session.getId()); executions.put(executionId, registeredSessions); } finally { mainLock.unlock(); } }
@OnOpen public void onOpen(Session session) { System.out.printf("WebSocket session opened, id: %s%n", session.getId()); ClientSession clientSession = new ClientSession(new MAVLinkWebSocket(session), mtMessageQueue); clientSession.onOpen(); sessions.put(session.getId(), clientSession); }
@OnOpen public void open(Session session) { try { session.getBasicRemote().sendText( "{\"topic\": \"title\", \"payload\": {\"title\":\"Application Metrics for Java\", \"docs\": \"http://github.com/RuntimeTools/javametrics\"}}"); } catch (IOException e) { e.printStackTrace(); } openSessions.add(session); DataHandler.registerEmitter(this); }
@OnOpen public void onOpen(@SuppressWarnings("unused") Session session, EndpointConfig config) { if (config == null) { throw new RuntimeException(); } }
@OnOpen public void onOpen(final Session session, EndpointConfig ec) { currentSession = session; agent = getRandomSupportAgent(); String greeting = getGreeting(agent); currentSession.getAsyncRemote().sendText(greeting); }
@OnOpen public void registerUser(Session websocket) throws IOException { Integer organisationId = Integer .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0)); Integer userId = getUser(websocket).getUserId(); if (!KumaliveWebsocketServer.getSecurityService().hasOrgRole(organisationId, userId, new String[] { Role.GROUP_MANAGER, Role.MONITOR, Role.LEARNER }, "register on kumalive", false)) { // prevent unauthorised user from accessing Kumalive String warning = "User " + userId + " is not a monitor nor a learner of organisation " + organisationId; logger.warn(warning); websocket.close(new CloseReason(CloseCodes.CANNOT_ACCEPT, warning)); } }
/** * Registeres the Learner for processing by SendWorker. */ @OnOpen public void registerUser(Session websocket) throws IOException { Long lessonId = Long.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_LESSON_ID).get(0)); Map<String, Session> sessionWebsockets = CommandWebsocketServer.websockets.get(lessonId); if (sessionWebsockets == null) { sessionWebsockets = new ConcurrentHashMap<String, Session>(); CommandWebsocketServer.websockets.put(lessonId, sessionWebsockets); } String login = websocket.getUserPrincipal().getName(); sessionWebsockets.put(login, websocket); }
@OnOpen public void handleOpen(Session userSession) { this.session = userSession; System.out.print("session open"); System.out.print("(" + UploadServlet.uploadTime() + ")"); }
@OnOpen public void open(final Session session) { sessions.add(session); /* Send list of students */ List<Student> students = requestBean.getAllStudents(); String studentList = jsonStudentList(students); try { session.getBasicRemote().sendText(studentList); } catch (IOException e) { log.log(Level.INFO, "[StatusEndpoint] {0}", e.getMessage()); } }
@OnOpen public void start(Session session) { this.session = session; connections.add(this); String message = String.format("* %s %s", nickname, "has joined."); broadcast(message); }
@OnOpen public void open(Session session, @PathParam(value = "user")String user) { Session session1 = sessionMap.get(user); if (null != session1) { try { session1.close(); } catch (IOException e) { e.printStackTrace(); } } sessionMap.put(user, session); log.info("*** WebSocket opened from sessionId " + session.getId()); }