@Test public void testClientDropsConnection() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(Bug58624Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); SimpleClient client = new SimpleClient(); URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH); Session session = wsContainer.connectToServer(client, uri); // Break point A required on following line session.close(); }
@OnMessage public void msgReceived(ChatMessage msg, Session s) { msg.from(user); if (msg.getMsg().equals(LOGOUT_MSG)) { try { s.close(); return; } catch (IOException ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex); } } ChatEventBus.getInstance().publishChat(msg); System.out.println("Chat Message placed on HZ Topic " + CHAT_TOPIC_NAME); }
@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); } } }); } }
/** * * Called by web socket server, message contain execution tracking status that updated on job canvas. * * @param message the message * @param session the session */ @OnMessage public void updateJobTrackingStatus(String message, Session session) { final String status = message; Display.getDefault().asyncExec(new Runnable() { public void run() { Gson gson = new Gson(); ExecutionStatus executionStatus=gson.fromJson(status, ExecutionStatus.class); IWorkbenchPage page = PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage(); IEditorReference[] refs = page.getEditorReferences(); for (IEditorReference ref : refs){ IEditorPart editor = ref.getEditor(false); if(editor instanceof ELTGraphicalEditor){ ELTGraphicalEditor editPart=(ELTGraphicalEditor)editor; if(editPart.getJobId().equals(executionStatus.getJobId()) || (((editPart.getContainer()!=null) && (editPart.getContainer().getUniqueJobId().equals(executionStatus.getJobId()))) && editPart.getContainer().isOpenedForTracking() )){ TrackingStatusUpdateUtils.INSTANCE.updateEditorWithCompStatus(executionStatus, (ELTGraphicalEditor)editor,false); } } } } }); }
private static Object[] buildArgs(PojoPathParam[] pathParams, Map<String, String> pathParameters, Session session, EndpointConfig config, Throwable throwable, CloseReason closeReason) throws DecodeException { Object[] result = new Object[pathParams.length]; for (int i = 0; i < pathParams.length; i++) { Class<?> type = pathParams[i].getType(); if (type.equals(Session.class)) { result[i] = session; } else if (type.equals(EndpointConfig.class)) { result[i] = config; } else if (type.equals(Throwable.class)) { result[i] = throwable; } else if (type.equals(CloseReason.class)) { result[i] = closeReason; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); try { result[i] = Util.coerceToType(type, value); } catch (Exception e) { throw new DecodeException(value, sm.getString("pojoMethodMapping.decodePathParamFail", value, type), e); } } } return result; }
/** * 连接建立成功调用的方法-与前端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); // 广播 }
@OnClose public void unregisterUser(Session websocket, CloseReason reason) throws JSONException, IOException { String login = websocket.getUserPrincipal().getName(); if (login == null) { return; } Integer organisationId = Integer .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0)); KumaliveDTO kumalive = kumalives.get(organisationId); if (kumalive == null) { return; } KumaliveUser user = kumalive.learners.remove(login); if (user != null) { Integer userId = user.userDTO.getUserID(); if (kumalive.raisedHand != null) { kumalive.raisedHand.remove(userId); } if (userId.equals(kumalive.speaker)) { kumalive.speaker = null; } } sendRefresh(kumalive); }
/**连接建立成功调用的方法*/ @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失败!"); } } }
/** * 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); }
/** * Tell learners that the teacher finished a question */ private void downHandPrompt(JSONObject requestJSON, Session websocket) throws IOException, JSONException { Integer organisationId = Integer .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0)); KumaliveDTO kumalive = kumalives.get(organisationId); User user = getUser(websocket); Integer userId = user.getUserId(); if (!KumaliveWebsocketServer.getSecurityService().hasOrgRole(organisationId, userId, new String[] { Role.GROUP_MANAGER, Role.MONITOR }, "kumalive down hand prompt", false)) { String warning = "User " + userId + " is not a monitor of organisation " + organisationId; logger.warn(warning); return; } kumalive.raiseHandPrompt = false; kumalive.raisedHand.clear(); if (logger.isDebugEnabled()) { logger.debug("Teacher " + userId + " finished a question in Kumalive " + kumalive.id); } sendRefresh(kumalive); }
public void broadcast(@Observes @LeaderDataQualifier String leaderboard) { for (final Session s : CLIENTS) { if (s != null && s.isOpen()) { /** * Asynchronous push */ s.getAsyncRemote().sendText(leaderboard, new SendHandler() { @Override public void onResult(SendResult result) { if (result.isOK()) { //Logger.getLogger(MeetupGroupsLiveLeaderboardEndpoint.class.getName()).log(Level.INFO, " sent to client {0}", s.getId()); } else { Logger.getLogger(MeetupGroupsLiveLeaderboardEndpoint.class.getName()).log(Level.SEVERE, "Could not send to client " + s.getId(), result.getException()); } } }); } } }
/** * * Close websocket client connection. * @param session */ public void closeWebSocketConnection(Session session){ try { Thread.sleep(DELAY); } catch (InterruptedException e1) { } if (session != null && session.isOpen()) { try { CloseReason closeReason = new CloseReason(CloseCodes.NORMAL_CLOSURE,"Closed"); session.close(closeReason); logger.info("Session closed"); } catch (IOException e) { logger.error("Fail to close connection ",e); } } }
@Override public final void onError(Session session, Throwable throwable) { if (methodMapping.getOnError() == null) { log.error(sm.getString("pojoEndpointBase.onError", pojo.getClass().getName()), throwable); } else { try { methodMapping.getOnError().invoke( pojo, methodMapping.getOnErrorArgs(pathParameters, session, throwable)); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("pojoEndpointBase.onErrorFail", pojo.getClass().getName()), t); } } }
/** * When user leaves the activity. */ @OnClose public void unregisterUser(Session websocket, CloseReason reason) { Long toolContentID = Long .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_CONTENT_ID).get(0)); websockets.get(toolContentID).remove(websocket); if (log.isDebugEnabled()) { // If there was something wrong with the connection, put it into logs. log.debug("User " + websocket.getUserPrincipal().getName() + " left Dokumaran with Tool Content ID: " + toolContentID + (!(reason.getCloseCode().equals(CloseCodes.GOING_AWAY) || reason.getCloseCode().equals(CloseCodes.NORMAL_CLOSURE)) ? ". Abnormal close. Code: " + reason.getCloseCode() + ". Reason: " + reason.getReasonPhrase() : "")); } }
public static synchronized void updateStatus2(Student student) { log.info("updateStatus2"); for (Session s : sessions) { if (s.isOpen()) { try { String studentUpdate = jsonStudentUpdate(student); s.getBasicRemote().sendText(studentUpdate); log.log(Level.INFO, "[StatusEndpoint] {0} is now {1}", new Object[]{student.getName(), student.getStatus()}); /* Send update */ } catch (IOException e) { log.log(Level.INFO, "[StatusEndpoint] {0}", e.getMessage()); } } } }
/** * 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); } }
@OnClose public void onClose(Session session) throws InterruptedException { ClientSession clientSession = sessions.get(session.getId()); if (clientSession != null) { clientSession.onClose(); sessions.remove(session.getId()); } System.out.printf("webSocket %s session closed.", session.getId()); }
@Test public void testWebSocket() throws IOException { final EchoEndpoint endpoint = new EchoEndpoint(); final Session session = getSession(); endpoint.onOpen(session); assertEquals("hello", endpoint.onMessage("hello", session)); endpoint.onClose(session); }
@Override public void onOpen(Session session, EndpointConfig config) { logger.debug("@onOpen"); wsClientSession = session; wsClientSession.addMessageHandler(this); sendSubscribeRequest(); }
private Session getSession() { final Basic basicRemote = mock(Basic.class); final Session session = mock(Session.class); when(session.getBasicRemote()).thenReturn(basicRemote); return session; }
Set<Session> getOpenSessions(Endpoint endpoint) { HashSet<Session> result = new HashSet<Session>(); synchronized (endPointSessionMapLock) { Set<WsSession> sessions = endpointSessionMap.get(endpoint); if (sessions != null) { result.addAll(sessions); } } return result; }
/** * Save score for a learner */ private void score(JSONObject requestJSON, Session websocket) throws IOException, JSONException { Integer organisationId = Integer .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0)); User user = getUser(websocket); Integer userId = user.getUserId(); if (!KumaliveWebsocketServer.getSecurityService().hasOrgRole(organisationId, userId, new String[] { Role.GROUP_MANAGER, Role.MONITOR }, "kumalive score", false)) { String warning = "User " + userId + " is not a monitor of organisation " + organisationId; logger.warn(warning); return; } Long rubricId = requestJSON.getLong("rubricId"); Integer learnerId = requestJSON.getInt(AttributeNames.PARAM_USER_ID); KumaliveWebsocketServer.getKumaliveService().scoreKumalive(rubricId, learnerId, Long.valueOf(requestJSON.getString("batch")), Short.valueOf(requestJSON.getString("score"))); KumaliveDTO kumalive = kumalives.get(organisationId); if (logger.isDebugEnabled()) { logger.debug("Teacher " + userId + " marked rubric " + rubricId + " for learner " + learnerId + " in Kumalive " + kumalive.id); } sendRefresh(kumalive); }
@OnMessage public void echoTextMessage(Session session, String msg, boolean last) { try { session.getBasicRemote().sendText(msg, last); } catch (IOException e) { try { session.close(); } catch (IOException e1) { // Ignore } } }
private void doTestPerMessageDefalteClient(String msg, int count) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME); List<Extension> extensions = new ArrayList<Extension>(1); extensions.add(perMessageDeflate); ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create().extensions(extensions).build(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, clientConfig, new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(count); BasicText handler = new BasicText(latch, msg); wsSession.addMessageHandler(handler); for (int i = 0; i < count; i++) { wsSession.getBasicRemote().sendText(msg); } boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); ((WsWebSocketContainer) wsContainer).destroy(); }
@OnMessage public void echoBinaryMessage(Session session, ByteBuffer bb, boolean last) { try { if (session.isOpen()) { session.getBasicRemote().sendBinary(bb, last); } } catch (IOException e) { try { session.close(); } catch (IOException e1) { // Ignore } } }
@OnMessage(maxMessageSize = MAX_SIZE) public void echoTextMessage(Session session, String msg) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { try { session.close(); } catch (IOException e1) { // Ignore } } }
@Override public void launchJob(String xmlPath, String paramFile,String userFunctionsPropertyFile, Job job, DefaultGEFCanvas gefCanvas,List<String> externalFiles,List<String> subJobList) { Session session=null; if(isExecutionTrackingOn()){ HydrographServerConnection hydrographServerConnection = new HydrographServerConnection(); session = hydrographServerConnection.connectToServer(job, job.getUniqueJobId(), webSocketLocalHost); if(hydrographServerConnection.getSelection() == 1){ TrackingDisplayUtils.INSTANCE.closeWebSocketConnection(session); return; } } String projectName = xmlPath.split("/", 2)[0]; IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); job.setJobProjectDirectory(project.getLocation().toOSString()); String gradleCommand; job.setJobStatus(JobStatus.RUNNING); JobManager.INSTANCE.enableRunJob(false); enableLockedResources(gefCanvas); gradleCommand = getExecututeJobCommand(xmlPath, paramFile,userFunctionsPropertyFile, job); executeCommand(job, project, gradleCommand, gefCanvas); if(job.getJobStatus().equalsIgnoreCase(JobStatus.RUNNING)){ job.setJobStatus(JobStatus.SUCCESS); } if (job.getCanvasName().equals(JobManager.INSTANCE.getActiveCanvas())) { JobManager.INSTANCE.enableRunJob(true); } refreshProject(gefCanvas); JobManager.INSTANCE.removeJob(job.getCanvasName()); ViewExecutionHistoryUtility.INSTANCE.addTrackingJobs(job.getConsoleName(), job); TrackingDisplayUtils.INSTANCE.closeWebSocketConnection(session); }
/** * 随机线程 * * @param wsPacket */ public void userMessageReceiveHandle(WsPacket wsPacket) { Session session = (Session) wsPacket.session; OnlineUser onlineUser = OnlineUserManager.getOnlineUserBySessionId(session.getId()); if (onlineUser == null) { WSManager.log.warn("发消息的非在线用户,直接返回"); return; } UserMessageReceiveC builder1 = (UserMessageReceiveC) wsPacket.getData(); boolean result = ChatAction.updateChat(builder1.getMessageIdList()); }
@Override public void onOpen(Session session, EndpointConfig endpointConfig) { ServerEndpointConfig sec = (ServerEndpointConfig) endpointConfig; Object pojo; try { pojo = sec.getConfigurator().getEndpointInstance( sec.getEndpointClass()); } catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "pojoEndpointServer.getPojoInstanceFail", sec.getEndpointClass().getName()), e); } setPojo(pojo); @SuppressWarnings("unchecked") Map<String,String> pathParameters = (Map<String, String>) sec.getUserProperties().get( POJO_PATH_PARAM_KEY); setPathParameters(pathParameters); PojoMethodMapping methodMapping = (PojoMethodMapping) sec.getUserProperties().get( POJO_METHOD_MAPPING_KEY); setMethodMapping(methodMapping); doOnOpen(session, endpointConfig); }
/** * 随机线程 * * @param wsPacket */ public void userMessageReceiveHandle(WsPacket wsPacket) { Session session = (Session) wsPacket.session; OnlineUserMongodb onlineUser = OnlineUserManagerMongodb.getOnlineUserBySessionId(session.getId()); if (onlineUser == null) { WSManager.log.warn("发消息的非在线用户,直接返回"); return; } UserMessageReceiveC builder1 = (UserMessageReceiveC) wsPacket.getData(); boolean result = ChatActionMongodb.updateChat(builder1.getMessageIdList(), builder1.getUserId(), onlineUser.getUserId()); }
/** * Save the session into the correct channel ID. * @param session session object. * @param id channel id. */ void add(Session session, Long id) { if(!sessions.containsKey(id)) { List<Session> tmp = new ArrayList<>(); tmp.add(session); sessions.put(id, tmp); } else { sessions.get(id).add(session); } }
@OnMessage(maxMessageSize = MAX_SIZE) public void echoBinaryMessage(Session session, ByteBuffer msg) { try { session.getBasicRemote().sendBinary(msg); } catch (IOException e) { try { session.close(); } catch (IOException e1) { // Ignore } } }
@OnMessage public void echoBinaryMessage(Session session, ByteBuffer msg, boolean last) { try { session.getBasicRemote().sendBinary(msg, last); } catch (IOException e) { try { session.close(); } catch (IOException e1) { // Ignore } } }
@OnMessage public void handleMessage(Session session, String message) throws IOException { logger.info("Received msg: " + message); String sendMsg = "Reversed: " + new StringBuilder(message).reverse(); session.getBasicRemote().sendText(sendMsg); logger.info("Send msg: " + sendMsg); }
@Override public Session get() { return session.updateAndGet(s -> { while (s == null || !s.isOpen()) { s = TimingUtils.retryOnFailure(() -> client.connectToServer(endpoint, endpointUri), reconnectDelay); } return s; }); }
@Test public void testConnectToServerEndpoint() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); // Set this artificially small to trigger // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054 wsContainer.setDefaultMaxBinaryMessageBufferSize(64); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText(MESSAGE_STRING_1); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); Queue<String> messages = handler.getMessages(); Assert.assertEquals(1, messages.size()); Assert.assertEquals(MESSAGE_STRING_1, messages.peek()); ((WsWebSocketContainer) wsContainer).destroy(); }
private void sendMessage(Session session, String message) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } }
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); } }