Java バックエンド + フロントエンドは WebSocket を使用してメッセージをプッシュします (プロセス + 詳細コード)
プロジェクトの開発中に、フロントエンド ページにデータをアクティブに送信するサーバーの機能を実現する必要性に遭遇しました。この機能を実現するにはポーリングとWebSocketの技術を使うしかありませんが、リアルタイム性とリソース消費を考慮した結果、最終的にWebSocketを使用することにしました。それでは、Java での Websocket テクノロジの実装を記録しましょう~
Java で Websocket を実装するには、通常 2 つの方法があります: 1. open、close、message、error などのメソッドを含む WebSocketServer クラスを作成する; 2. webSocketHandler を使用するSpringboot によって提供されるクラスを使用してその子クラスを作成し、メソッドをオーバーライドします。私たちのプロジェクトは Springboot フレームワークを使用していますが、依然として最初の方法を採用しています。
WebSocketの簡単な動作プロセス例を作成する
1. Websocket 依存関係を導入する
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.0</version>
</dependency>
2. 構成クラス WebSocketConfig を作成します
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3. WebSocketServerの作成
WebSocket プロトコルでは、バックエンド サーバーは ws のクライアントに相当します。@ServerEndpoint を使用してアクセス パスを指定し、@Component を使用してコンテナに挿入する必要があります。
@ServerEndpoint: ServerEndpointExporter クラスが宣言され、Spring 構成を通じて使用されると、@ServerEndpoint アノテーションが付けられたクラスがスキャンされます。アノテーションが付けられたクラスは、WebSocket エンドポイントとして登録されます。すべての構成項目はこのアノテーションの属性内にあります
(例: @ServerEndpoint("/ws") )
次の例では、 @ServerEndpoint は、アクセス パスに各ページを区別するために使用される sid が含まれていることを指定しています。
import com.alibaba.fastjson.JSONObject;
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.net.Socket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint("/notice/{userId}")
@Component
@Slf4j
public class NoticeWebsocket {
//记录连接的客户端
public static Map<String, Session> clients = new ConcurrentHashMap<>();
/**
* userId关联sid(解决同一用户id,在多个web端连接的问题)
*/
public static Map<String, Set<String>> conns = new ConcurrentHashMap<>();
private String sid = null;
private String userId;
/**
* 连接成功后调用的方法
* @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 + "连接开启!");
}
/**
* 连接关闭调用的方法
*/
@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;
}
}
/**
* 发送给所有用户
* @param noticeType
*/
public static void sendMessage(String noticeType){
NoticeWebsocketResp noticeWebsocketResp = new NoticeWebsocketResp();
noticeWebsocketResp.setNoticeType(noticeType);
sendMessage(noticeWebsocketResp);
}
/**
* 发送给所有用户
* @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();
}
}
}
/**
* 根据用户id发送给某一个用户
* **/
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();
}
}
}
}
}
}
/**
* 收到客户端消息后调用的方法
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+this.userId+"的信息:"+message);
}
/**
* 发生错误时的回调函数
* @param error
*/
@OnError
public void onError(Throwable error) {
log.info("错误");
error.printStackTrace();
}
}
送信メッセージをカプセル化したオブジェクトを直接使用できます。
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("ws通知返回对象")
public class NoticeWebsocketResp<T> {
@ApiModelProperty(value = "通知类型")
private String noticeType;
@ApiModelProperty(value = "通知内容")
private T noticeInfo;
}
4. Webソケット呼び出し
ユーザーはインターフェイスを呼び出し、情報をバックエンドにアクティブに送信します。バックエンドは情報を受信した後、指定された/すべてのユーザーに情報をアクティブにプッシュします。
@RestController
@RequestMapping("/order")
public class OrderController {
@GetMapping("/test")
public R test() {
NoticeWebsocket.sendMessage("你好,WebSocket");
return R.ok();
}
}
フロントエンドWebSocket接続
<!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() {
var ws = new WebSocket('ws://192.168.2.88:9060/notice/1');
// 获取连接状态
console.log('ws连接状态:' + ws.readyState);
//监听是否连接成功
ws.onopen = function () {
console.log('ws连接状态:' + ws.readyState);
limitConnect = 0;
//连接成功则发送一个数据
ws.send('我们建立连接啦');
}
// 接听服务器发回的信息并处理展示
ws.onmessage = function (data) {
console.log('接收到来自服务器的消息:');
console.log(data);
//完成通信后关闭WebSocket连接
// ws.close();
}
// 监听连接关闭事件
ws.onclose = function () {
// 监听整个过程中websocket的状态
console.log('ws连接状态:' + ws.readyState);
reconnect();
}
// 监听并处理error事件
ws.onerror = function (error) {
console.log(error);
}
}
function reconnect() {
limitConnect ++;
console.log("重连第" + limitConnect + "次");
setTimeout(function(){
init();
},2000);
}
</script>
</html>
プロジェクト開始後、コンソールはページを開いた後に接続情報を出力し、
フロントエンドはorder/testメソッドを呼び出した後、プッシュメッセージの内容を出力すること
で、WebSocket通信はURLを呼び出して行うことができます。インターフェイスまたは ws~
フロントエンド ページがない場合は、オンライン WebSocket テストを使用することもできます