WebSocket–入門
公司領(lǐng)導(dǎo)提出了一個(gè)新的需求,那就是部門主管在有審批消息的情況下,需要看到提示消息。其實(shí)這種需求最簡(jiǎn)單的方法使接入短信、郵件、公眾號(hào)平臺(tái)。直接推送消息。但是,由于使自研項(xiàng)目,公司領(lǐng)導(dǎo)不想花錢,只能另辟蹊徑。
WebSocket簡(jiǎn)介
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工(full-duplex)通信,即允許服務(wù)器主動(dòng)發(fā)送信息給客戶端。因此,在WebSocket中,瀏覽器和服務(wù)器只需要完成一次握手,兩者之間就直接可以創(chuàng)建持久性的連接,并進(jìn)行雙向數(shù)據(jù)傳輸,客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡(jiǎn)單。
WebSocket-實(shí)現(xiàn)后端推送消息給前端
依賴導(dǎo)入
<!-- 該依賴包含 SpringBoot starer 無需重復(fù)導(dǎo)入 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.0</version>
</dependency>
<!-- 除此之外我們還需要lombok 和 fastjson -->
<!-- 這里就不導(dǎo)入了 -->
代碼實(shí)現(xiàn)
WebSocketConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketMessage–封裝的消息結(jié)果類(非必須)
import lombok.Data;
@Data
public class NoticeWebsocketResp<T> {
private String noticeType;
private T noticeInfo;
}
WebSocketServer
import com.alibaba.fastjson.JSONObject;
import com.mydemo.websocketdemo.domain.NoticeWebsocketResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/notice/{userId}")
@Component
@Slf4j
public class NoticeWebsocket {
//記錄連接的客戶端
public static Map<String, Session> clients = new ConcurrentHashMap<>();
/**
* userId關(guān)聯(lián)sid(解決同一用戶id,在多個(gè)web端連接的問題)
*/
public static Map<String, Set<String>> conns = new ConcurrentHashMap<>();
private String sid = null;
private String userId;
/**
* 連接成功后調(diào)用的方法
* @param session
* @param userId
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.sid = UUID.randomUUID().toString();
this.userId = userId;
clients.put(this.sid, session);
Set<String> clientSet = conns.get(userId);
if (clientSet==null){
clientSet = new HashSet<>();
conns.put(userId,clientSet);
}
clientSet.add(this.sid);
log.info(this.sid + "連接開啟!");
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
log.info(this.sid + "連接斷開!");
clients.remove(this.sid);
}
/**
* 判斷是否連接的方法
* @return
*/
public static boolean isServerClose() {
if (NoticeWebsocket.clients.values().size() == 0) {
log.info("已斷開");
return true;
}else {
log.info("已連接");
return false;
}
}
/**
* 發(fā)送給所有用戶
* @param noticeType
*/
public static void sendMessage(String noticeType){
NoticeWebsocketResp noticeWebsocketResp = new NoticeWebsocketResp();
noticeWebsocketResp.setNoticeType(noticeType);
sendMessage(noticeWebsocketResp);
}
/**
* 發(fā)送給所有用戶
* @param noticeWebsocketResp
*/
public static void sendMessage(NoticeWebsocketResp noticeWebsocketResp){
String message = JSONObject.toJSONString(noticeWebsocketResp);
for (Session session1 : NoticeWebsocket.clients.values()) {
try {
session1.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根據(jù)用戶id發(fā)送給某一個(gè)用戶
* **/
public static void sendMessageByUserId(String userId, NoticeWebsocketResp noticeWebsocketResp) {
if (!StringUtils.isEmpty(userId)) {
String message = JSONObject.toJSONString(noticeWebsocketResp);
Set<String> clientSet = conns.get(userId);
if (clientSet != null) {
Iterator<String> iterator = clientSet.iterator();
while (iterator.hasNext()) {
String sid = iterator.next();
Session session = clients.get(sid);
if (session != null) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* 收到客戶端消息后調(diào)用的方法
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到來自窗口"+this.userId+"的信息:"+message);
}
/**
* 發(fā)生錯(cuò)誤時(shí)的回調(diào)函數(shù)
* @param error
*/
@OnError
public void onError(Throwable error) {
error.printStackTrace();
}
}
這樣我們就配置好了websocket
測(cè)試準(zhǔn)備
訪問接口–當(dāng)請(qǐng)求該接口時(shí),主動(dòng)推送消息
import com.mydemo.websocketdemo.domain.NoticeWebsocketResp;
import com.mydemo.websocketdemo.websocketserver.NoticeWebsocket;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/order")
public class OrderController {
@GetMapping("/test")
public String test() {
NoticeWebsocket.sendMessage("你好,WebSocket");
return "ok";
}
@GetMapping("/test1")
public String test1() {
NoticeWebsocketResp noticeWebsocketResp = new NoticeWebsocketResp();
noticeWebsocketResp.setNoticeInfo("米奇妙妙屋");
NoticeWebsocket.sendMessageByUserId("1", noticeWebsocketResp);
return "ok";
}
}
springboot啟動(dòng)類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebSocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebSocketApplication.class,args);
}
}
前端測(cè)試頁(yè)面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SseEmitter</title>
</head>
<body>
<div id="message"></div>
</body>
<script>
var limitConnect = 0;
init();
function init() {
// 8080未默認(rèn)端口,可自行替換
var ws = new WebSocket('ws://localhost:8080/notice/2');
// 獲取連接狀態(tài)
console.log('ws連接狀態(tài):' + ws.readyState);
//監(jiān)聽是否連接成功
ws.onopen = function () {
console.log('ws連接狀態(tài):' + ws.readyState);
limitConnect = 0;
//連接成功則發(fā)送一個(gè)數(shù)據(jù)
ws.send('我們建立連接啦');
}
// 接聽服務(wù)器發(fā)回的信息并處理展示
ws.onmessage = function (data) {
console.log('接收到來自服務(wù)器的消息:');
console.log(data);
//完成通信后關(guān)閉WebSocket連接
// ws.close();
}
// 監(jiān)聽連接關(guān)閉事件
ws.onclose = function () {
// 監(jiān)聽整個(gè)過程中websocket的狀態(tài)
console.log('ws連接狀態(tài):' + ws.readyState);
reconnect();
}
// 監(jiān)聽并處理error事件
ws.onerror = function (error) {
console.log(error);
}
}
function reconnect() {
limitConnect ++;
console.log("重連第" + limitConnect + "次");
setTimeout(function(){
init();
},2000);
}
</script>
</html>
之后用瀏覽器打開html頁(yè)面,顯示如下:
連接成功
調(diào)用接口文章來源:http://www.zghlxwxcb.cn/news/detail-696259.html
localhost:8080/order/test
證明后端推送消息給前端成功文章來源地址http://www.zghlxwxcb.cn/news/detail-696259.html
到了這里,關(guān)于websockets-后端主動(dòng)向前端推送消息的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!