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

void close(CloseStatus status) throws IOException;

Source Link

Document

Close the WebSocket connection with the given close status.

Usage

From source file:org.springframework.messaging.simp.stomp.StompWebSocketHandler.java

/**
 * Handle STOMP messages going back out to WebSocket clients.
 *//*from w ww.j  a va2 s  .c  o m*/
@Override
public void handleMessage(Message<?> message) {

    StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
    headers.setCommandIfNotSet(StompCommand.MESSAGE);

    if (StompCommand.CONNECTED.equals(headers.getCommand())) {
        // Ignore for now since we already sent it
        return;
    }

    String sessionId = headers.getSessionId();
    if (sessionId == null) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, no sessionId header: " + message);
        return;
    }

    WebSocketSession session = this.sessions.get(sessionId);
    if (session == null) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, sessionId not found: " + message);
        return;
    }

    if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, no subscriptionId header: " + message);
        return;
    }

    if (!(message.getPayload() instanceof byte[])) {
        // TODO: failed message delivery mechanism
        logger.error("Ignoring message, expected byte[] content: " + message);
        return;
    }

    try {
        message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
        byte[] bytes = this.stompMessageConverter.fromMessage(message);
        session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8"))));
    } catch (Throwable t) {
        sendErrorMessage(session, t);
    } finally {
        if (StompCommand.ERROR.equals(headers.getCommand())) {
            try {
                session.close(CloseStatus.PROTOCOL_ERROR);
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.java

public static void tryCloseWithError(WebSocketSession session, Throwable exception, Log logger) {
    if (logger.isErrorEnabled()) {
        logger.error("Closing session due to exception for " + session, exception);
    }//from  ww  w.ja  v  a  2 s  . c o  m
    if (session.isOpen()) {
        try {
            session.close(CloseStatus.SERVER_ERROR);
        } catch (Throwable ex) {
            // ignore
        }
    }
}

From source file:org.springframework.web.socket.messaging.StompSubProtocolHandler.java

private void sendToClient(WebSocketSession session, StompHeaderAccessor stompAccessor, byte[] payload) {
    StompCommand command = stompAccessor.getCommand();
    try {//w  w w .ja va 2  s . c  o m
        byte[] bytes = this.stompEncoder.encode(stompAccessor.getMessageHeaders(), payload);
        boolean useBinary = (payload.length > 0 && !(session instanceof SockJsSession)
                && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(stompAccessor.getContentType()));
        if (useBinary) {
            session.sendMessage(new BinaryMessage(bytes));
        } else {
            session.sendMessage(new TextMessage(bytes));
        }
    } catch (SessionLimitExceededException ex) {
        // Bad session, just get out
        throw ex;
    } catch (Throwable ex) {
        // Could be part of normal workflow (e.g. browser tab closed)
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to send WebSocket message to client in session " + session.getId(), ex);
        }
        command = StompCommand.ERROR;
    } finally {
        if (StompCommand.ERROR.equals(command)) {
            try {
                session.close(CloseStatus.PROTOCOL_ERROR);
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
}

From source file:org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.java

/**
 * Handle an outbound Spring Message to a WebSocket client.
 *//*  w  ww.j  av a  2  s .  c o  m*/
@Override
public void handleMessage(Message<?> message) throws MessagingException {
    String sessionId = resolveSessionId(message);
    if (sessionId == null) {
        if (logger.isErrorEnabled()) {
            logger.error("Could not find session id in " + message);
        }
        return;
    }

    WebSocketSessionHolder holder = this.sessions.get(sessionId);
    if (holder == null) {
        if (logger.isDebugEnabled()) {
            // The broker may not have removed the session yet
            logger.debug("No session for " + message);
        }
        return;
    }

    WebSocketSession session = holder.getSession();
    try {
        findProtocolHandler(session).handleMessageToClient(session, message);
    } catch (SessionLimitExceededException ex) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Terminating '" + session + "'", ex);
            }
            this.stats.incrementLimitExceededCount();
            clearSession(session, ex.getStatus()); // clear first, session may be unresponsive
            session.close(ex.getStatus());
        } catch (Exception secondException) {
            logger.debug("Failure while closing session " + sessionId + ".", secondException);
        }
    } catch (Exception ex) {
        // Could be part of normal workflow (e.g. browser tab closed)
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to send message to client in " + session + ": " + message, ex);
        }
    }
}

From source file:org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.java

/**
 * When a session is connected through a higher-level protocol it has a chance
 * to use heartbeat management to shut down sessions that are too slow to send
 * or receive messages. However, after a WebSocketSession is established and
 * before the higher level protocol is fully connected there is a possibility for
 * sessions to hang. This method checks and closes any sessions that have been
 * connected for more than 60 seconds without having received a single message.
 *///from  w w w  .java2 s  . c o m
private void checkSessions() {
    long currentTime = System.currentTimeMillis();
    if (!isRunning() || (currentTime - this.lastSessionCheckTime < TIME_TO_FIRST_MESSAGE)) {
        return;
    }

    if (this.sessionCheckLock.tryLock()) {
        try {
            for (WebSocketSessionHolder holder : this.sessions.values()) {
                if (holder.hasHandledMessages()) {
                    continue;
                }
                long timeSinceCreated = currentTime - holder.getCreateTime();
                if (timeSinceCreated < TIME_TO_FIRST_MESSAGE) {
                    continue;
                }
                WebSocketSession session = holder.getSession();
                if (logger.isInfoEnabled()) {
                    logger.info("No messages received after " + timeSinceCreated + " ms. " + "Closing "
                            + holder.getSession() + ".");
                }
                try {
                    this.stats.incrementNoMessagesReceivedCount();
                    session.close(CloseStatus.SESSION_NOT_RELIABLE);
                } catch (Throwable ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Failed to close unreliable " + session, ex);
                    }
                }
            }
        } finally {
            this.lastSessionCheckTime = currentTime;
            this.sessionCheckLock.unlock();
        }
    }
}

From source file:org.springframework.web.socket.support.ExceptionWebSocketHandlerDecorator.java

public static void tryCloseWithError(WebSocketSession session, Throwable exception, Log logger) {
    logger.error("Closing due to exception for " + session, exception);
    if (session.isOpen()) {
        try {/*ww w .  jav a  2 s  .  c om*/
            session.close(CloseStatus.SERVER_ERROR);
        } catch (Throwable t) {
            // ignore
        }
    }
}