Example usage for org.springframework.web.socket WebSocketSession isOpen

List of usage examples for org.springframework.web.socket WebSocketSession isOpen

Introduction

In this page you can find the example usage for org.springframework.web.socket WebSocketSession isOpen.

Prototype

boolean isOpen();

Source Link

Document

Return whether the connection is still open.

Usage

From source file:com.pubkit.platform.messaging.protocol.pkmp.PKMPInBoundEventHandler.java

private void handlePublish(PKMPPublish publish, WebSocketSession session) {
    String topic = publish.getTopic();
    if (topic == null || "".equals(topic)) {
        LOG.debug("PKMPPublish failed. Null or empty topic name.");

        PKMPPubAck errorAck = new PKMPPubAck(publish.getClientId(), topic, PKMPPubAck.INVALID_TOPIC);
        sendPayload(errorAck, session);/*from  w  ww  .j  av  a 2s.co m*/

        return;
    }
    boolean tokenValid = validateAccessToken(publish.getClientId(), publish.getSessionToken(), session);
    if (!tokenValid) {
        LOG.error("Client {" + publish.getClientId() + "} failed to publish on topic {" + topic
                + "}. Invalid token");
        PKMPPubAck errorAck = new PKMPPubAck(publish.getClientId(), topic, PKMPSubsAck.INVALID_TOKEN);
        sendPayload(errorAck, session);

        return;
    }

    List<PKMPConnection> subscribers = messageStoreService.getAllSubscribers(topic);
    for (PKMPConnection subscriber : subscribers) {
        if (subscriber.getClientId().equals(publish.getClientId())) {
            continue;
        }
        WebSocketSession subscriberSession = messageStoreService.getSession(subscriber.getSessionId());
        if (subscriberSession != null && subscriberSession.isOpen()) {
            PKMPPubMessage pKMPPubMessage = new PKMPPubMessage(subscriber.getClientId(), publish.getClientId());
            pKMPPubMessage.setTopic(publish.getTopic());
            pKMPPubMessage.setMessageId(publish.getMessageId());
            pKMPPubMessage.setData(publish.getData());

            sendPayload(pKMPPubMessage, subscriberSession);
        } else {
            LOG.debug("Session not found for client with client id {" + subscriber.getClientId() + "} "
                    + "and session id {" + subscriber.getSessionId() + "}");

            // send push notification if possible for inactive subscriber
            handleInactiveSubscriber(subscriber, publish.getMessageId());

            if (subscriberSession != null) {
                sendDisconnect(subscriber.getClientId(), subscriberSession);
            }
        }
        statsService.incrMessageCount();
    }
    sendPayload(new PKMPPubAck(publish.getClientId(), topic), session);
}

From source file:com.github.mrstampy.gameboot.websocket.WebSocketSessionRegistry.java

private boolean sessionCheck(String groupName, WebSocketSession wss) {
    boolean open = wss.isOpen();

    if (!open) {/* ww w .ja  v  a2  s  . c om*/
        log.warn("Session {} is closed in group {}, cannot send message", wss.getId(), groupName);
        removeFromGroup(groupName, wss);
    }

    return open;
}

From source file:com.github.mrstampy.gameboot.websocket.WebSocketSessionRegistry.java

/**
 * Sends the message to the {@link WebSocketSession} specified by the
 * {@link AbstractRegistryKey}./*w  w w.  j a va  2 s  .  c  o  m*/
 *
 * @param key
 *          the key
 * @param message
 *          the message
 */
public void send(AbstractRegistryKey<?> key, String message) {
    checkMessage(message);

    WebSocketSession session = get(key);
    if (session == null || !session.isOpen()) {
        log.warn("Cannot send message to {}, no session", key);
        return;
    }

    sendText(GROUP_OF_ONE, session, message);
}

From source file:com.github.mrstampy.gameboot.websocket.WebSocketSessionRegistry.java

/**
 * Sends the message to the {@link WebSocketSession} specified by the
 * {@link AbstractRegistryKey}./*from   w w w .  jav  a  2  s .  c o m*/
 *
 * @param key
 *          the key
 * @param message
 *          the message
 */
public void send(AbstractRegistryKey<?> key, byte[] message) {
    checkMessage(message);

    WebSocketSession session = get(key);
    if (session == null || !session.isOpen()) {
        log.warn("Cannot send message to {}, no session", key);
        return;
    }

    sendBinary(GROUP_OF_ONE, session, message);
}

From source file:cn.com.inhand.devicenetworks.ap.websocket.WSDNAccessPoint.java

/**
 * ?Inbox/*from  w ww. j  a  va2s  . c o m*/
 *
 * @param login
 */
private void onLogin(DNMessage login, WebSocketSession session, WSDNSession wsdnsn)
        throws PacketException, IOException {
    if (login.getName().equals("login") && login.getType() == 0) {
        int result = auth(login);
        //API??
        if (result != 0) {
            List list = new ArrayList();
            list.add(new Parameter("result", "" + result));
            list.add(new Parameter("reason", ""));
            DNMessage ack = new DNMessage("login", "response", login.getTxid(), list);
            session.sendMessage(new TextMessage(new String(parser.wrap(ack))));
            list.clear();

            throw new PacketException("Failed to Login!");
        } else {
            //for debug
            if (login.getParameter("id").getValue().equals("1111")) {

                List list = new ArrayList();
                list.add(new Parameter("result", "21336"));
                list.add(new Parameter("reason", ""));
                DNMessage ack = new DNMessage("login", "response", login.getTxid(), list);
                session.sendMessage(new TextMessage(new String(parser.wrap(ack))));
                list.clear();

                throw new PacketException("The token is invalid!");
            } else {
                List list = new ArrayList();
                list.add(new Parameter("result", "0"));
                list.add(new Parameter("reason", ""));
                DNMessage ack = new DNMessage("login", "response", login.getTxid(), list);
                session.sendMessage(new TextMessage(new String(parser.wrap(ack))));
                list.clear();
                wsdnsn = new WSDNSession(login, session);
                wsdnsn.setAction(1);
                wsdnsn.setId(login.getParameter("id").getValue());
                wsdnsn.setIsLogin(true);
                wsdnsn.setAssetid(login.getParameter("asset_id").getValue());
                wsdnsn.setSn(login.getParameter("sn").getValue());
                wsdnsn.setToken(login.getParameter("access_token").getValue());

                wsdnsn.setKey(login.getParameter("key").getValue());
                wsdnsn.setId(login.getParameter("id").getValue());
                wsdnsn.setConnection_time(System.currentTimeMillis());
                wsdnsn.setLast_msg(wsdnsn.getConnection_time());

                //map
                this.cinfo.putWsdnsn(session.toString(), wsdnsn);
                try {
                    WebSocketSession oldSession = this.cinfo.getWssn(wsdnsn.getId());
                    if (oldSession != null && oldSession.isOpen()) {
                        List list1 = new ArrayList();
                        list1.add(new Parameter("result", "23010"));
                        list1.add(new Parameter("reason", "A new session is established"));
                        DNMessage logout = new DNMessage("logout", "request", "MSG_FROM_SMARTVMS-1", list1);
                        oldSession.sendMessage(new TextMessage(new String(parser.wrap(logout))));
                        oldSession.close();
                    }
                } catch (Exception e) {

                }
                this.cinfo.putWssn(wsdnsn.getId(), session);
                //this.isLogin = true;
            }
        }

    } else {
        throw new PacketException("The Packet is not a login packet!");
    }
}

From source file:com.zb.app.websocket.server.WebSocketServerHandler.java

/**
 * session?/* w w  w.ja v a  2s  . c  om*/
 */
public void sessionClosed(WebSocketSession session) {
    if (session != null && !session.isOpen()) {
        logger.debug("sessionClosed session is closed!by auto sessionClosed");
        removeSession(session);
        return;
    }
    if (session != null && session.isOpen()) {
        removeSession(session);
    }
}

From source file:virnet.experiment.webSocket.hndler.MainSystemWebSocketHandler.java

@Override
public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception {
    if (wss.isOpen()) {
        if (expUsers.contains(wss))
            expUsers.remove(wss);//from w  ww .  j a  v  a2s .c  om
        else
            arrangeUsers.remove(wss);
        wss.close();
    }
    System.out.println("websocket connection closed......ERROR");
}

From source file:virnet.experiment.webSocket.hndler.MainSystemWebSocketHandler.java

public void sendToGroup(WebSocketSession wss, JSONObject jsonString) {

    String groupid = userMap.get(wss);
    String mess = jsonString.toString();
    System.out.println(groupid);/*from  w  w  w  .j  a v a  2 s.  co  m*/

    for (WebSocketSession user : expUsers) {
        try {
            if (user.isOpen() && (userMap.get(user).equals(groupid))) {
                user.sendMessage(new TextMessage(mess));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:com.navercorp.pinpoint.web.websocket.ActiveThreadCountHandler.java

private void handleActiveThreadCount(WebSocketSession webSocketSession, RequestMessage requestMessage) {
    final String applicationName = MapUtils.getString(requestMessage.getParameters(), APPLICATION_NAME_KEY);
    if (applicationName != null) {
        final WebSocketSessionContext sessionContext = getSessionContext(webSocketSession);
        synchronized (lock) {
            if (StringUtils.equals(applicationName, sessionContext.getApplicationName())) {
                return;
            }/* w w w .  j  a v  a2 s  .c  o m*/

            unbindingResponseAggregator(webSocketSession, sessionContext);
            if (webSocketSession.isOpen()) {
                bindingResponseAggregator(webSocketSession, sessionContext, applicationName);
            } else {
                logger.warn("WebSocketSession is not opened. skip binding.");
            }
        }
    }
}

From source file:com.zb.app.websocket.server.WebSocketServerHandler.java

/**
 * ?????// w w  w . jav a2 s .c  o m
 * 
 * @param receiverMessage
 * @param session
 */
public void clientHeartbeat(SocketMessage<?> receiverMessage, WebSocketSession session) {
    ClientWrapper cw = receiverMessage.getClientInfo();
    SessionWrapper sw = getSessionInfo(session);
    String json = JsonResultUtils.createJsonResult(ResultCode.HEARTBEAT, "$zuobian$",
            "Server zxc,hello world!");
    if (session == null) {
        return;
    }
    if (session != null && !session.isOpen()) {
        removeSession(session);
    }
    try {
        session.sendMessage(new TextMessage(json));
        if (sw != null) {
            sw.setLastHeartbeatTime(System.currentTimeMillis());
        }
        logger.debug("clientHeartbeat sessionId={} ,mId={},cId={}, date={}", sw.getId(), cw.getmId(),
                cw.getWebUser().getcId(), DateViewTools.formatFullDate(new Date()));
    } catch (Exception e) {
        if (System.currentTimeMillis() - sw.getLastHeartbeatTime() >= 1000 * 60 * 5) { // 5??Client
            removeSession(session);
        }
        logger.debug("clientHeartbeat send errorsessionId={} ,mId={},cId={}, date={}", sw.getId(),
                cw.getmId(), cw.getWebUser().getcId(), DateViewTools.formatFullDate(new Date()));
    }
}