2015-11-28 94 views
3

我正在用Spring Boot,RabbitMQ和WebSocket構建一個網絡聊天作爲POC,但我被困在最後一點:WebSockets
我想讓我的客戶端連接到特定的端點,比如/room/{id},當新消息到達時,我希望服務器向客戶端發送響應,但我搜索了類似的東西,但沒有找到。春天:發送消息給websocket客戶端

目前,郵件到達時,我的RabbitMQ處理它,就像

container.setMessageListener(new MessageListenerAdapter(){ 
      @Override 
      public void onMessage(org.springframework.amqp.core.Message message, Channel channel) throws Exception { 
       log.info(message); 
       log.info("Got: "+ new String(message.getBody())); 
      } 
     }); 

我想什麼,而不是記錄它,我想將它發送給客戶端,例如:websocketManager.sendMessage(new String(message.getBody()))

回答

3

好吧,我想我得到了它,大家誰需要它,這裏是答案:

首先,你需要WS依賴添加到pom.xml中

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-websocket</artifactId> 
</dependency> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-messaging</artifactId> 
</dependency> 

創建WS端點

@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { 

    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 
     // the endpoint for websocket connections 
     registry.addEndpoint("/stomp").withSockJS(); 
    } 

    @Override 
    public void configureMessageBroker(MessageBrokerRegistry config) { 
     config.enableSimpleBroker("/"); 

     // use the /app prefix for others 
     config.setApplicationDestinationPrefixes("/app"); 
    } 

} 

注:我使用STOMP,所以客戶應該象這樣連接

<script type="text/javascript"> 
    $(document).ready(function() { 
     var messageList = $("#messages"); 
     // defined a connection to a new socket endpoint 
     var socket = new SockJS('/stomp'); 
     var stompClient = Stomp.over(socket); 
     stompClient.connect({ }, function(frame) { 
      // subscribe to the /topic/message endpoint 
      stompClient.subscribe("/room.2", function(data) { 
       var message = data.body; 
       messageList.append("<li>" + message + "</li>"); 
      }); 

     }); 
    }); 
</script> 

然後,你可以簡單地連線上與你的組件的WS使者

@Autowired 
private SimpMessagingTemplate webSocket; 

,併發送與

消息
webSocket.convertAndSend(channel, new String(message.getBody())); 
+0

「channel」來自哪裏作爲convertAndSend的目標參數? –

+0

通道是一個字符串。它是我發送消息的「房間」,例如「/ room」。concat(message.getRoom()。getUid()。toString())' –

相關問題