spring boot(二)websocket

spring boot 與 webSocketweb

1. 廣播式spring

1. 在配置類中使用@EnableWebSocketMessageBroker開啓websocket支持。瀏覽器

StompEndpointRegistry.addEndpoint(「/endpointWisely」).withSocketJS();  //註冊STOMP協議的節點,配置制定的url服務器

StompEndpointRegistry.enableSimpleBroker(「/topic」);  //配置消息代理,也是服務端發送消息的url前綴websocket

2.控制器中app

@Controllersocket

public class WsController{ide

@MessageMapping(「/hello」) //瀏覽器請求路徑工具

@SendTo(「/topic/getResponse」) url

public WiselyResponse say(WiselyMessage message){

return new WiselyResponse(「hello」+message);

}

3.頁面JS中

var socket = new SockJS(‘/endpointWisely’); //對應config中配置的節點url

stompClient.subscribe(‘/topic/getResponse’) //訂閱,瀏覽器—>服務器,對應controller中@sendTo註解的路徑

stompClient.send(‘/hello’) //發送消息,服務器—>瀏覽器,對應controller中@MessageMapping註解的路徑

2.點對點式

SimpMessagingTemplate是Spring-WebSocket內置的一個消息發送工具,能夠將消息發送到指定的客戶端。

@Controller

public class WsController{

@Autowired

private SimpMessagingTemplate simpMessagingTemplate;

@MessageMapping(「/point2p」) //瀏覽器請求路徑

public void say(String message){

simpMessagingTemplate.convertAndSendToUser(「接受消息的用戶」,」/topic/getResponse」, message);

}

}

且js中路徑stompClient.subscribe(‘/user/topic/getResponse’),多了一個/user,表示發送消息到指定用戶。

相關文章
相關標籤/搜索