和服務器保存長連接,不是http,首先和客服端建立連接
1.導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.實現接口WebSocketMessageBrokerConfigurer,重寫註冊請求和信息代理方法
@Configuration
@EnableWebSocketMessageBroker
public class SocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* 註冊請求
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//配置建立 websocket客服端請求地址,withSockJS前端用它
registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
}
/**
* 配置消息代理
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue"); //用戶點對點聊
}
}
3.接受用戶msg對象,發送給某用戶
/**
* 點對點聊天
*/
@Controller
public class WsController {
/**
* Simp消息發送
*/
@Autowired
SimpMessagingTemplate simpMessagingTemplate;
/**
*
* @param principal 獲取用戶登陸狀態
* @param msg 信息對象
*/
@MessageMapping("/ws/chat")
public void receive(Principal principal,Msg msg){
String from = principal.getName(); //用戶對象
msg.setFrom(from); //從哪裏來
simpMessagingTemplate.convertAndSendToUser(msg.getTo(),"/queue/chat",msg);//發給某地址用戶
}
4.定義一個msg信息對象
/**
* 消息對象
*/
public class Msg implements Serializable {
private String content; //信息內容
private String from; //從哪裏來
private String to; //發信息
前端一段重要代碼
initCon() {
let _this = this;
this.stomp = Stomp.over(new SockJS('/ws/ep'));//配置websocket 連接
this.stomp.connect({},success=>{
_this.stomp.subscribe('/user/queue/chat',msg=>{ //監聽訂閱服務端"/queue/chat"信息
_this.msgs.push(JSON.parse(msg.body))
})
},failed=>{
});//建立websocket 連接
},
send() {
this.stomp.send('/ws/chat', {}, JSON.stringify(this.msg)); //發信息到/ws/chat服務器控制層方法
}