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

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

Introduction

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

Prototype

@Override
void close() throws IOException;

Source Link

Document

Close the WebSocket connection with status 1000, i.e.

Usage

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

/**
 * After connection established.//from  ww w  . j a v  a2 s  . c  om
 *
 * @param session
 *          the session
 * @throws Exception
 *           the exception
 */
@SuppressWarnings("unchecked")
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    boolean encrypted = ((AbstractWebSocketSession<Session>) session).getNativeSession().isSecure();

    if (!encrypted) {
        log.error("Not an encrypted web socket {}, disconnecting", session.getRemoteAddress());
        session.close();
    }

    super.afterConnectionEstablished(session);
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

private byte[] extractArray(WebSocketSession session, BinaryMessage message) throws IOException {
    ByteBuffer buf = message.getPayload();

    if (buf.hasArray())
        return buf.array();

    int size = buf.remaining();

    if (size == 0) {
        log.error("No message, closing session {}", session);
        session.close();
        return null;
    }//from   w  w w  .  ja v  a2s .c  o  m

    byte[] b = new byte[size];

    buf.get(b, 0, b.length);

    return b;
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

/**
 * Process for binary./*from ww  w .  j a  v a  2s . c  o m*/
 *
 * @param session
 *          the session
 * @param msg
 *          the msg
 * @throws Exception
 *           the exception
 */
protected void processForBinary(WebSocketSession session, byte[] msg) throws Exception {
    OtpKeyRequest message = converter.fromJson(msg);

    if (!validateChannel(session, message))
        return;

    Response r = processor.process(message);

    if (r == null || !r.isSuccess()) {
        log.error("Unexpected response {}, disconnecting {}", r, session);
        session.close();
        return;
    }

    BinaryMessage bm = new BinaryMessage(converter.toJsonArray(r));
    session.sendMessage(bm);

    log.debug("Successful send of {} to {}", message.getType(), session.getRemoteAddress());

    Thread.sleep(50);
    session.close(CloseStatus.NORMAL);
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
    svc.execute(() -> {//from w  w w .ja va 2s  . com
        try {
            byte[] array = extractArray(session, message);
            if (array != null)
                processForBinary(session, array);
        } catch (Exception e) {
            log.error("Unexpected exception, disconnecting {}", session, e);
            try {
                session.close();
            } catch (Exception e1) {
                log.error("Unexpected exception closing session {}", session, e1);
            }
        }
    });
}

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

/**
 * Extract payload./*from   ww  w  .  ja  v a2  s  .co  m*/
 *
 * @param session
 *          the session
 * @param msg
 *          the msg
 * @return the object
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
protected Object extractPayload(WebSocketSession session, Object msg) throws IOException {
    if (msg instanceof BinaryMessage) {
        return ((BinaryMessage) msg).getPayload().array();
    } else if (msg instanceof TextMessage) {
        return ((TextMessage) msg).getPayload();
    }

    log.error("Only strings or byte arrays: {} from {}. Disconnecting", msg.getClass(), session);
    session.close();

    return null;
}

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

@Override
public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs) throws Exception {
    if (expUsers.contains(wss))
        expUsers.remove(wss);/* ww w.ja  va 2s . co  m*/
    else
        arrangeUsers.remove(wss);
    wss.close();
    System.out.println("websocket connection closed......CLOSE");
}

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);//ww  w  . j av  a2s .  c o m
        else
            arrangeUsers.remove(wss);
        wss.close();
    }
    System.out.println("websocket connection closed......ERROR");
}

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

/**
 * ?Inbox/*  w  w  w  .j  a  v  a2  s .c om*/
 *
 * @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.github.sshw.websocket.SSHWebSocketHandler.java

@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
    if (!(message instanceof TextMessage)) {
        throw new IllegalStateException("Unexpected WebSocket message type: " + message);
    }/* ww w .  ja v a  2 s. c  om*/
    String messageText = ((TextMessage) message).getPayload();
    SSHSession sshSession = sshSessionManager.sessionsByWebsocketID.get(session.getId());
    if (sshSession == null) {
        log.info("linking {}:{}", session.getId(), messageText);
        // TODO is there a better way to do this?
        // Can the client send the websocket session id and username in a REST call to link them up?
        sshSession = sshSessionManager.sessionsByUsername.get(messageText);
        sshSession.setWebSocketSession(session);
        sshSessionManager.sessionsByWebsocketID.put(session.getId(), sshSession);
    } else {
        log.debug("message in {}:{}", session.getId(), messageText);
        sshSession.getSSHOutput().write((messageText + '\n').getBytes());
        sshSession.getSSHOutput().flush();
    }
    // if we receive a valid logout command, then close the websocket session.
    // the system will logout and tidy itself up...
    if (logoutCommands.contains(messageText.trim().toLowerCase())) {
        log.info("valid logout command received: {}", messageText);
        session.close();
    }
}

From source file:org.opencron.server.websocket.TerminalHandler.java

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    super.afterConnectionEstablished(session);
    String sshSessionId = OpencronTools.getSshSessionId();
    if (sshSessionId != null) {
        final Terminal terminal = TerminalContext.remove(sshSessionId);
        if (terminal != null) {
            try {
                session.sendMessage(new TextMessage("Welcome to Opencron Terminal! Connect Starting."));
                getClient(session, terminal);
                int cols = Integer.parseInt(session.getAttributes().get("cols").toString());
                int rows = Integer.parseInt(session.getAttributes().get("rows").toString());
                int width = Integer.parseInt(session.getAttributes().get("width").toString());
                int height = Integer.parseInt(session.getAttributes().get("height").toString());
                terminalClient.openTerminal(cols, rows, width, height);
                terminalService.login(terminal);
            } catch (Exception e) {
                if (e.getLocalizedMessage().replaceAll("\\s+", "").contentEquals("Operationtimedout")) {
                    session.sendMessage(new TextMessage("Sorry! Connect timed out, please try again. "));
                } else {
                    session.sendMessage(new TextMessage("Sorry! Operation error, please try again. "));
                }/* w  w w. ja  v  a 2 s.com*/
                terminalClient.disconnect();
                session.close();
            }
        } else {
            this.terminalClient.disconnect();
            session.sendMessage(new TextMessage("Sorry! Connect failed, please try again. "));
            session.close();
        }
    }
}