WebSocket を使用するのは初めてなので、非常に簡単な例が必要ですが、これを実行すると、このテクノロジに対する理解が深まります。(技術的な基本的な紹介は省略し、後ほど補足します)
ケース ロジック: 現在ユーザーは 1 人だけで、1 人のユーザーがサーバーにデータを送信し、サービスがユーザーにデータを返します。
1. SpringBoot は WebSocket を統合します
ここのロジックには 3 つのステップがあります
最初のステップは依存関係を追加することです
2 番目のステップは構成を追加することです
3 番目に、基本的なサービス クラスを作成します。
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. 基本的なサービスツール
@ServerEndpoint(value = "/ws/{userId}")
@Component
@Slf4j
public class WebSocketServer {
private String userId;
/**
* @param session 是webSocket的会话对象,不是浏览器那个session
* @param userId 用户Id
* @description 当连接建立成功调用
**/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.userId = userId;
System.out.println("建立连接");
}
/**
* @param session 会话对象
* @description 当连接关闭调用
**/
@OnClose
public void onClose(Session session) throws IOException {
System.out.println("关闭连接");
}
/**
* @param message 客户端发送的消息
* @param session 会话对象
* @description 当客户端发送消息时调用
**/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
try{
System.out.println(message);
//给客户端发送消息
session.getBasicRemote().sendText("服务端定义的消息");
}catch(Exception e){
e.printStackTrace();
}
}
}
2. uniapp はサーバーと通信するための webSocket を構築します
フロントエンドロジック
ステップ 1: サーバーとの接続を確立する
ステップ 2: WebSocket 接続オープン イベントをリッスンし、このリッスン イベントでサーバーにデータをアクティブに送信します。
ステップ 3: WebSocket がサーバーから受信するメッセージ イベントを監視します (サーバーにメッセージを送信すると、時間内にフロントエンドにもデータが返されます)。
1. 具体的なコード
function webSocketFun(Integer userId){
//1. 通过用户唯一id 与 服务端webSocket建立连接
uni.connectSocket({
url: `http://192.168.2.18:8080/ws/${userId}`
});
//2. 监听WebSocket连接打开事件,并给服务端发送消息
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. 监听WebSocket接受到服务器的消息事件
uni.onSocketMessage(function (res) {
console.log('收到服务器返回的内容为 ======' + res.data);
});
}