2
votes

I am fairly new with Spring websocket. I have a simple demo below:

HandshakeInterceptor class:

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 class:

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 }));
    }

Now i want to send a message to a specific user. I define each device have a deviceId, so i want to know:

  1. How to handshake with attributes, which will be send from client?
  2. How to send handshake attributes from client javascript?
  3. How to send message from server to client by handshake attributes?

Thank you for your attention.

1

1 Answers

4
votes

You can use the session is to save the deviceId

session.setAttribute("deviceId",deviceId);

And in the 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);
        }
    }

In the WebsocketEndPoint.java,you need a method like

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;
        }
    }
}

You can send a message to a specific user from the server