2014-06-06 117 views
1

我對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. 如何通過握手屬性將消息從服​​務器發送到客戶端?

感謝您的關注。

回答

3

您可以使用會話保存的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; 
     } 
    } 
} 
的方法

您可以從服務器發送郵件給特定用戶

相關問題