javax.websocket.Session#isOpen ( )源码实例Demo

下面列出了javax.websocket.Session#isOpen ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: uyuni   文件: VirtNotifications.java
/**
 * 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);
        }
    }
}
 
源代码2 项目: quarks   文件: WebSocketClientConnector.java
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);
            }
        }
    }
}
 
源代码3 项目: tomcatsrc   文件: DrawboardEndpoint.java
@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);
    }
}
 
源代码4 项目: Tomcat8-Source-Read   文件: DrawboardEndpoint.java
@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);
    }
}
 
源代码5 项目: lams   文件: CommandWebsocketServer.java
/**
 * 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());
	}
    }
}
 
源代码6 项目: o2oa   文件: ActionCreate.java
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;
}
 
源代码7 项目: tomcatsrc   文件: EchoAnnotation.java
@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
        }
    }
}
 
源代码8 项目: Tomcat7.0.67   文件: TestWsWebSocketContainer.java
private int getOpenCount(Set<Session> sessions) {
    int result = 0;
    for (Session session : sessions) {
        if (session.isOpen()) {
            result++;
        }
    }
    return result;
}
 
源代码9 项目: OneBlog   文件: WebSocketUtil.java
/**
 * 群发
 *
 * @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);
        }
    }
}
 
源代码10 项目: javaee7-websocket   文件: MatchEndpoint.java
/**
 * 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());
    }   
}
 
源代码11 项目: jeecg-boot   文件: WebSocket.java
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();
            }
        }
	}
    
}
 
源代码12 项目: tomcatsrc   文件: EchoAnnotation.java
@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
        }
    }
}
 
@Override
protected void closeConnection() throws Exception {
	try {
		Session session = this.session;
		if (session != null && session.isOpen()) {
			session.close();
		}
	}
	finally {
		this.session = null;
	}
}
 
源代码14 项目: ipst   文件: WebSocketContext.java
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();
        }
    }
}
 
@Override
protected void closeConnection() throws Exception {
	try {
		Session session = this.session;
		if (session != null && session.isOpen()) {
			session.close();
		}
	}
	finally {
		this.session = null;
	}
}
 
源代码16 项目: uyuni   文件: Notification.java
/**
 * 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);
}
 
源代码17 项目: symphonyx   文件: TimelineChannel.java
/**
 * 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);
            }
        }
    }
}
 
源代码18 项目: tomcatsrc   文件: EchoAnnotation.java
@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
        }
    }
}
 
源代码19 项目: uyuni   文件: VirtNotifications.java
/**
 * 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);
}
 
源代码20 项目: teaching   文件: WebSocket.java
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();
        }
    }
}