Java Code Examples for javax.websocket.Session#isOpen()

The following examples show how to use javax.websocket.Session#isOpen() . 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: WebSocketClientConnector.java    From quarks with Apache License 2.0 6 votes vote down vote up
void sendBinary(byte[] bytes) {
    while (true) {
        Session session = getConnectedSession();
        try {
            session.getBasicRemote().sendBinary(ByteBuffer.wrap(bytes));
            getLogger().trace("{} sendBinary {} bytes.", id(), bytes.length);
            return;
        }
        catch (IOException e) {
            if (!session.isOpen()) {
                connectionLost(e);  // logs error
                // retry
            }
            else {
                getLogger().error("{} sendBinary failed", id(), e);
                throw new RuntimeException(e);
            }
        }
    }
}
 
Example 2
Source File: ActionCreate.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
	ActionResult<Wo> result = new ActionResult<>();
	Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
	Wo wo = new Wo();
	wo.setValue(false);

	for (Entry<Session, String> entry : ActionCollaboration.clients.entrySet()) {
		if (StringUtils.equals(entry.getValue(), wi.getPerson())) {
			Session session = entry.getKey();
			if (session != null && session.isOpen()) {
				logger.debug(effectivePerson, "send ws, message: {}.", wi);
				session.getBasicRemote().sendText(jsonElement.toString());
				wo.setValue(true);
			}
		}
	}

	result.setData(wo);
	return result;
}
 
Example 3
Source File: CommandWebsocketServer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Feeds opened websockets with commands.
 */
private void send(Long lessonId) throws IOException {
    Long lastSendTime = lastSendTimes.get(lessonId);
    if (lastSendTime == null) {
	lastSendTime = System.currentTimeMillis() - ILearnerService.COMMAND_WEBSOCKET_CHECK_INTERVAL;
    }
    lastSendTimes.put(lessonId, System.currentTimeMillis());

    List<Command> commands = CommandWebsocketServer.getLearnerService().getCommandsForLesson(lessonId,
	    new Date(lastSendTime));
    Map<String, Session> lessonWebsockets = CommandWebsocketServer.websockets.get(lessonId);
    for (Command command : commands) {
	Session websocket = lessonWebsockets.get(command.getUserName());
	if (websocket != null && websocket.isOpen()) {
	    websocket.getBasicRemote().sendText(command.getCommandText());
	}
    }
}
 
Example 4
Source File: DrawboardEndpoint.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void onError(Session session, Throwable t) {
    // Most likely cause is a user closing their browser. Check to see if
    // the root cause is EOF and if it is ignore it.
    // Protect against infinite loops.
    int count = 0;
    Throwable root = t;
    while (root.getCause() != null && count < 20) {
        root = root.getCause();
        count ++;
    }
    if (root instanceof EOFException) {
        // Assume this is triggered by the user closing their browser and
        // ignore it.
    } else if (!session.isOpen() && root instanceof IOException) {
        // IOException after close. Assume this is a variation of the user
        // closing their browser (or refreshing very quickly) and ignore it.
    } else {
        log.error("onError: " + t.toString(), t);
    }
}
 
Example 5
Source File: DrawboardEndpoint.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(Session session, Throwable t) {
    // Most likely cause is a user closing their browser. Check to see if
    // the root cause is EOF and if it is ignore it.
    // Protect against infinite loops.
    int count = 0;
    Throwable root = t;
    while (root.getCause() != null && count < 20) {
        root = root.getCause();
        count ++;
    }
    if (root instanceof EOFException) {
        // Assume this is triggered by the user closing their browser and
        // ignore it.
    } else if (!session.isOpen() && root instanceof IOException) {
        // IOException after close. Assume this is a variation of the user
        // closing their browser (or refreshing very quickly) and ignore it.
    } else {
        log.error("onError: " + t.toString(), t);
    }
}
 
Example 6
Source File: VirtNotifications.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Must be synchronized. Sending messages concurrently from separate threads
 * will result in IllegalStateException.
 *
 * @param session the WebSocket session
 * @param message the message to be sent
 */
public static void sendMessage(Session session, String message) {
    synchronized (session) {
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
            else {
                LOG.debug(String.format("Could not send websocket message. Session [id:%s] is closed.",
                        session.getId()));
                handbreakSession(session);
            }
        }
        catch (IOException e) {
            LOG.error("Error sending websocket message", e);
            handbreakSession(session);
        }
    }
}
 
Example 7
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private int getOpenCount(Set<Session> sessions) {
    int result = 0;
    for (Session session : sessions) {
        if (session.isOpen()) {
            result++;
        }
    }
    return result;
}
 
Example 8
Source File: EchoAnnotation.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@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
        }
    }
}
 
Example 9
Source File: WebSocketUtil.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 群发
 *
 * @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 10
Source File: MatchEndpoint.java    From javaee7-websocket with MIT License 5 votes vote down vote up
/**
 * When the match is finished, each peer which has bet on this match receive a message.
 * @param winner
 * @param matchId
 */
public static void sendBetMessages(String winner, String matchId, boolean isFinished) {
    try {
        /* Send updates to all open WebSocket sessions for this match */
        for (Session session : peers) {
        	if (Boolean.TRUE.equals(session.getUserProperties().get(matchId))){
        		if (session.isOpen()){
        			if (session.getUserProperties().containsKey("bet")){
        				BetMessage betMsg = new BetMessage((String)session.getUserProperties().get("bet"));
        				if (isFinished){
         				if (winner != null 
          					&& winner.equals(betMsg.getWinner())){
          				betMsg.setResult("OK");
          			} else {
          				betMsg.setResult("KO");
          			}
        				}
        				sendBetMessage(session, betMsg, matchId);
                  logger.log(Level.INFO, "Result Sent: {0}", betMsg.getResult());
        			}
    			}
        		if (isFinished){
     			//Match finished, need to clear properties
         		session.getUserProperties().clear();
         		nbBetsByMatch.get(matchId).set(0);
        		}
    		}
        }
        logger.log(Level.INFO, "Match FINISHED");
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.toString());
    }   
}
 
Example 11
Source File: WebSocket.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
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 12
Source File: EchoAnnotation.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
    try {
        if (session.isOpen()) {
            session.getBasicRemote().sendText(msg, last);
        }
    } catch (IOException e) {
        try {
            session.close();
        } catch (IOException e1) {
            // Ignore
        }
    }
}
 
Example 13
Source File: AnnotatedEndpointConnectionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void closeConnection() throws Exception {
	try {
		Session session = this.session;
		if (session != null && session.isOpen()) {
			session.close();
		}
	}
	finally {
		this.session = null;
	}
}
 
Example 14
Source File: WebSocketContext.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public synchronized void send(Message message) {
    for (Iterator<Session> it =  sessions.iterator(); it.hasNext();) {
        Session session = it.next();
        if (session.isOpen()) {
            try {
                session.getBasicRemote().sendObject(message);
            } catch (Exception e) {
                LOGGER.error(e.toString(), e);
            }
        } else {
            it.remove();
        }
    }
}
 
Example 15
Source File: EndpointConnectionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void closeConnection() throws Exception {
	try {
		Session session = this.session;
		if (session != null && session.isOpen()) {
			session.close();
		}
	}
	finally {
		this.session = null;
	}
}
 
Example 16
Source File: Notification.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Callback executed an error occurs.
 * @param session the WebSocket session
 * @param err the err that occurred
 */
@OnError
public void onError(Session session, Throwable err) {
    Boolean didClientAbortedConnection = err instanceof EOFException ||
            !session.isOpen() ||
            err.getMessage().startsWith("Unexpected error [32]");

    if (didClientAbortedConnection) {
        LOG.debug("The client aborted the connection.", err);
    }
    else {
        LOG.error("Websocket endpoint error", err);
    }
    handbreakSession(session);
}
 
Example 17
Source File: TimelineChannel.java    From symphonyx with Apache License 2.0 5 votes vote down vote up
/**
 * Notifies the specified comment message to browsers.
 *
 * @param message the specified message, for example      <pre>
 * {
 *     "commentContent": ""
 * }
 * </pre>
 */
public static void notifyTimeline(final JSONObject message) {
    final String msgStr = message.toString();

    synchronized (SESSIONS) {
        for (final Session session : SESSIONS) {
            if (session.isOpen()) {
                session.getAsyncRemote().sendText(msgStr);
            }
        }
    }
}
 
Example 18
Source File: EchoAnnotation.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@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
        }
    }
}
 
Example 19
Source File: VirtNotifications.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Callback executed an error occurs.
 * @param session the websocket session
 * @param err the err that occurred
 */
@OnError
public void onError(Session session, Throwable err) {
    Boolean didClientAbortedConnection = err instanceof EOFException ||
            !session.isOpen() ||
            err.getMessage().startsWith("Unexpected error [32]");

    if (didClientAbortedConnection) {
        LOG.debug("The client aborted the connection.", err);
    }
    else {
        LOG.error("Websocket endpoint error", err);
    }
    handbreakSession(session);
}
 
Example 20
Source File: WebSocket.java    From teaching with Apache License 2.0 5 votes vote down vote up
public void sendOneMessage(String userId, String message) {
    Session session = sessionPool.get(userId);
    if (session != null&&session.isOpen()) {
        try {
        	log.info("【websocket消息】 单点消息:"+message);
            session.getAsyncRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}