下面列出了javax.websocket.Session#isOpen ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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);
}
}
}
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);
}
}
}
}
@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);
}
}
@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);
}
}
/**
* 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());
}
}
}
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;
}
@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
}
}
}
private int getOpenCount(Set<Session> sessions) {
int result = 0;
for (Session session : sessions) {
if (session.isOpen()) {
result++;
}
}
return result;
}
/**
* 群发
*
* @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);
}
}
}
/**
* 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());
}
}
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();
}
}
}
}
@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;
}
}
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;
}
}
/**
* 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);
}
/**
* 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);
}
}
}
}
@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
}
}
}
/**
* 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);
}
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();
}
}
}