2

我对 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映射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 回答 1

4

你可以使用session来保存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;
        }
    }
}

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

于 2014-08-19T03:23:40.160 回答