第一次使用WebSocket,所以最需要一個及其簡單的例子,跑通之后,增加自己對該技術(shù)的理解。(技術(shù)基礎(chǔ)介紹就免掉了,后面再補(bǔ))
?案例邏輯:目前只有一個用戶,而且是一個用戶給服務(wù)器發(fā)送數(shù)據(jù),服務(wù)給該用戶返回數(shù)據(jù)
一、SpringBoot 整合 WebSocket
此處的邏輯一共三步
第一步,添加依賴項
第二步,添加配置
第三,寫基礎(chǔ)服務(wù)類
?1. 添加websocket依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<!--需要版本的自己加-->
</dependency>
2. 添加配置
@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter 作用
*
* 這個Bean會自動注冊使用@ServerEndpoint注解聲明的websocket endpoint
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3. 基礎(chǔ)服務(wù)工具類
@ServerEndpoint(value = "/ws/{userId}")
@Component
@Slf4j
public class WebSocketServer {
private String userId;
/**
* @param session 是webSocket的會話對象,不是瀏覽器那個session
* @param userId 用戶Id
* @description 當(dāng)連接建立成功調(diào)用
**/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.userId = userId;
System.out.println("建立連接");
}
/**
* @param session 會話對象
* @description 當(dāng)連接關(guān)閉調(diào)用
**/
@OnClose
public void onClose(Session session) throws IOException {
System.out.println("關(guān)閉連接");
}
/**
* @param message 客戶端發(fā)送的消息
* @param session 會話對象
* @description 當(dāng)客戶端發(fā)送消息時調(diào)用
**/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
try{
System.out.println(message);
//給客戶端發(fā)送消息
session.getBasicRemote().sendText("服務(wù)端定義的消息");
}catch(Exception e){
e.printStackTrace();
}
}
}
二、uniapp 構(gòu)建webSocket與服務(wù)器通信
前端邏輯
第一步:跟服務(wù)器建立連接
第二步:監(jiān)聽WebSocket連接打開事件,并在這個監(jiān)聽事件中,主動給服務(wù)端發(fā)送數(shù)據(jù)
第三步:監(jiān)聽WebSocket接受到服務(wù)器的消息事件(你給服務(wù)器發(fā)送消息時,它也會及時給前端返回數(shù)據(jù))文章來源:http://www.zghlxwxcb.cn/news/detail-686263.html
1. 具體代碼
function webSocketFun(Integer userId){
//1. 通過用戶唯一id 與 服務(wù)端webSocket建立連接
uni.connectSocket({
url: `http://192.168.2.18:8080/ws/${userId}`
});
//2. 監(jiān)聽WebSocket連接打開事件,并給服務(wù)端發(fā)送消息
var socketOpen = false;
var socketMsgQueue = ["滕","禹","鑫"];
uni.onSocketOpen(function (res) {
console.log('WebSocket連接已打開');
socketOpen = true;
for (var i = 0; i < socketMsgQueue.length; i++) {
sendSocketMessage(socketMsgQueue[i]);
}
socketMsgQueue = [];
});
function sendSocketMessage(msg) {
if (socketOpen) {
uni.sendSocketMessage({
data: msg
});
} else {
socketMsgQueue.push(msg);
}
}
//3. 監(jiān)聽WebSocket接受到服務(wù)器的消息事件
uni.onSocketMessage(function (res) {
console.log('收到服務(wù)器返回的內(nèi)容為 ======' + res.data);
});
}
?文章來源地址http://www.zghlxwxcb.cn/news/detail-686263.html
到了這里,關(guān)于(一)SpringBoot 整合WebSocket 前端 uniapp 訪問的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!