如何通过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);
}

}

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. 如何通过握手属性从服务器发送消息到客户端?

感谢您的关注

可以使用会话id保存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;
        }
    }
}

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

相关内容

  • 没有找到相关文章

最新更新