马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
概要分析
signalr 是微软对 websocket技能的封装;
- build() 与后端signalR服务创建链接;
- 利用 on 方法监听后端界说的函数;ps:由后端发起,后端向前端发送数据
- 利用 invoke 自动触发后端的函数;ps:由前端发起,前端向后端发送哀求
安装依靠
- pnpm install @microsoft/signalr --save
复制代码 组件封装
- import * as signalR from "@microsoft/signalr";
- const serverUrl = "https://youraddress";
- class WebSocketManager {
- constructor() {
- this.connection = null;
- this.connectionStatus = 'disconnected';
- }
- createWebSocket(fileId) {
- this.connectionStatus = 'connecting';
- return new Promise((resolve, reject) => {
- try {
- this.connection = new signalR.HubConnectionBuilder()
- .withAutomaticReconnect()//断线自动重连
- .withUrl(`${serverUrl}?fileId=${fileId}`)
- .build();
- //启动连接
- this.connection.start().then(() => {
- console.log("SignalR server 连接成功");
- this.connectionStatus = 'connected';
- resolve(this.connectionStatus);
- }).catch((err) => {
- this.connectionStatus = 'error'
- console.error("SignalR server 连接失败", err);
- reject(err);
- });
- } catch (error) {
- console.error('Failed to start connection:', error);
- this.connectionStatus = 'error';
- reject(err);
- }
- });
- }
- //获取状态
- getConnectionStatus() {
- return this.connectionStatus;
- }
- //获取连接对象
- getConnection() {
- return this.connection;
- }
- //断开连接
- stopWebSocket() {
- if (this.getConnectionStatus() === 'connected') {
- this.connection.stop().then(() => {
- this.connectionStatus = 'disconnected';
- console.log("SignalR server 连接断开");
- }).catch((err) => {
- console.error("SignalR server 连接断开失败", err);
- });
- }
- }
- //发送消息
- sendMsg(msg) {
- if (this.getConnectionStatus() !== 'connected') {
- return console.error("SignalR server 未连接,无法发送消息");
- }
- this.connection.invoke("SendMessage", msg).catch((err) => {
- console.error("SignalR server 发送消息失败", err);
- });
- }
- //监听消息
- // receiveMsg() {
- // return new Promise((resolve, reject) => {
- // // console.log("receiveMsg=======>FileProcess");
- // this.connection.on("HeartBeat", (msg) => {
- // console.log("接收消息成功========>", msg);
- // resolve(msg);
- // })
- // })
- // }
- }
- export default new WebSocketManager();
复制代码 利用案例
- // 使用示例
- const signalRService = new SignalRService('链接地址');
- signalRService.start()
- .then(() => console.log('SignalR service started'))
- .catch(error => console.error('Failed to start SignalR service:', error));
- // 在需要的时候发送消息
- signalRService.send('Hello, SignalR!')
- .then(() => console.log('Message sent'))
- .catch(error => console.error('Failed to send message:', error));
- // 接收消息
- signalRService.receiveMessage((message: string) => {
- console.log("Received message:", message);
- }, "后端定义的方法名称(获取由后端给前端发送的数据)")
- // 停止连接
- signalRService.stop();
复制代码 |