如何通过spring websocket向特定设备发送消息

时间:2014-06-06 04:05:53

标签: javascript spring websocket spring-websocket

我对Spring websocket相当新。我在下面有一个简单的演示:

HandshakeInterceptor类:

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

private static final Log logger = LogFactory
        .getLog(HandshakeInterceptor.class);

@Override
public boolean beforeHandshake(ServerHttpRequest request,
        ServerHttpResponse response, WebSocketHandler wsHandler,
        Map<String, Object> attributes) throws Exception {
    logger.info("Before Handshake");
    return super.beforeHandshake(request, response, wsHandler, attributes);
}

@Override
public void afterHandshake(ServerHttpRequest request,
        ServerHttpResponse response, WebSocketHandler wsHandler,
        Exception ex) {
    logger.info("After Handshake");
    super.afterHandshake(request, response, wsHandler, ex);
}

}

WebsocketEndPoint类:

public class WebsocketEndPoint extends TextWebSocketHandler {

private static final Log logger = LogFactory
        .getLog(WebsocketEndPoint.class);

@Override
protected void handleTextMessage(WebSocketSession session,
        TextMessage message) throws Exception {
    super.handleTextMessage(session, message);
    logger.info("Recieved Message: " + message.getPayload());
    TextMessage returnMessage = new TextMessage(message.getPayload()
            + " received at server");
    logger.info("Return Message: " + returnMessage.getPayload());
    session.sendMessage(returnMessage);
}

}

Spring mapping websocket:

<bean id="websocket"
    class="com.n9.api.websocket.handler.WebsocketEndPoint" />

<websocket:handlers>
    <websocket:mapping path="/websocket" handler="websocket" />
    <websocket:handshake-interceptors>
        <bean
            class="com.n9.api.websocket.HandshakeInterceptor" />
    </websocket:handshake-interceptors>
</websocket:handlers>

HTML:

function connect() {
        if ('WebSocket' in window){
              console.log('Websocket supported');
              socket = new WebSocket('ws://localhost:8080/n9-api/websocket');

              console.log('Connection attempted');

              socket.onopen = function(){
                   console.log('Connection open!');
              }

              socket.onclose = function(){
                  console.log('Disconnecting connection');
              }

              socket.onmessage = function (evt) 
                 { 
                    var received_msg = evt.data;
                    console.log(received_msg);
                    console.log('message received!');
                 }

            } else {
              console.log('Websocket not supported');
            }
    }

    function disconnect() {
        setConnected(false);
        console.log("Disconnected");
    }

    function sendMessage(message) {
        socket.send(JSON.stringify({ 'message': message }));
    }

现在我想向特定用户发送消息。我定义每个设备都有一个deviceId,所以我想知道:

  1. 如何与属性握手,这些属性将从客户端发送?
  2. 如何从客户端javascript发送握手属性?
  3. 如何通过握手属性从服务器向客户端发送消息?
  4. 感谢您的关注。

1 个答案:

答案 0 :(得分:4)

您可以使用会话来保存deviceId

session.setAttribute("deviceId",deviceId);

在HandshakeInterceptor.java中

if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpSession session = servletRequest.getServletRequest().getSession(false);
        if (session != null) {

            String deviceId= (String) session.getAttribute("deviceId");
            attributes.put("websockt_deviceId",deviceId);
        }
    }

在WebsocketEndPoint.java中,您需要一个像

这样的方法
private static final ArrayList<WebSocketSession> sessions;    
public void sendMessageToUser(String deviceId, TextMessage message) {
    for (WebSocketSession session: sessions) {
        if (session.getAttributes().get("websockt_deviceId").equals(deviceId)) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
    }
}

您可以从服务器向特定用户发送消息