vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > 前端vue使用signalr

前端vue中使用signalr的方法举例详解

作者:小芝麻咿呀

在现代Web应用程序中,即时通讯功能已成为不可或缺的一部分,下面这篇文章主要介绍了前端vue中使用signalr的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

一、引入SignalR库

使用NPM引入SignalR库

npm install @microsoft/signalr

Js文件中引入

import * as signalR from '@microsoft/signalr';

二、初始化连接

这一步需要指定SignalR Hub的URL。

const connection = new signalR.HubConnectionBuilder()
	.withUrl("https://yourserver.com/hub/myhub")
	.build();

参数说明

在使用 SignalR 的 HubConnectionBuilder 时,可以通过链式方法配置连接的各个参数。以下是完整的参数配置写法和说明:

const connection = new signalR.HubConnectionBuilder()
    // 必填:设置 Hub 的 URL
    .withUrl(url, options) 
    // 可选:配置日志
    .configureLogging(logging) 
    // 可选:配置自动重连
    .withAutomaticReconnect(retryPolicy) 
    // 可选:配置自定义 HTTP 客户端
    .withHubProtocol(protocol) 
    // 构建连接对象
    .build();

1. withUrl

2. configureLogging

3. withAutomaticReconnect

4. withHubProtocol

5. build

完整示例

const connection = new signalR.HubConnectionBuilder()
    .withUrl("https://example.com/chathub", {
        transport: signalR.HttpTransportType.WebSockets,
        accessTokenFactory: () => localStorage.getItem("token"),
        skipNegotiation: true,
        headers: { "X-Client-Version": "1.0.0" }
    })
    .configureLogging(signalR.LogLevel.Debug)
    .withAutomaticReconnect([0, 1000, 5000, 10000])
    .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol())
    .build();

// 启动连接
connection.start()
    .then(() => console.log("Connected!"))
    .catch(err => console.error("Connection failed:", err));

其他配置(通过 withUrl 的 options)

根据实际需求选择配置项,确保兼容 SignalR 客户端库的版本。

三、启动连接

启动连接是指让前端与SignalR Hub建立实际的连接。

connection.start().then(() => {
	console.log("SignalR Connected.");
}).catch(err => {
    console.error(err.toString());
});

四、定义客户端方法(客户端接收服务端信息)

客户端方法是指SignalR Hub调用时客户端执行的函数。通过这些方法,前端可以响应来自服务器的实时通知。

// 实时接收服务端信息(服务端-->客户端)
connection.on('监听后端命名的方法A返回的数据:名称一般和invoke配套',(message) => {
	console.log('接受的信息Info message:', message);
	// 做一些赋值操作,把后端传来的数据渲染到页面
});
// 例:
connection.on("ReceiveMessage", (user, message) => {
    const msg = `${user}: ${message}`;
    const li = document.createElement("li");
    li.textContent = msg;
    document.getElementById("messagesList").appendChild(li);
});

五、发送消息到服务器

前端可以通过调用SignalR Hub的方法来发送消息到服务器。通常,这些方法是用户操作(如点击按钮)触发的。

// 客户端与服务端进行沟通(客户端-->服务端),客户端调取后端的方法进行通讯,后端返回信息
connection.invoke("后端命名的方法A", "一些后端需要的变量根据自己需求填写")
// 例:
connection.invoke('SendData', 'Hello, SignalR!');

六、实际应用场景

七、完整案例

以下是一个在 Vue 3 中使用 SignalR 实现连接、发送和接收数据的完整案例,包含详细注释和关键配置:

1. 安装依赖

npm install @microsoft/signalr

2. 创建 SignalR 工具类(可选)

在 src/utils/signalR.js 中封装连接逻辑:

import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr'

export default {
  // 创建连接
  createConnection(url, options = {}) {
    return new HubConnectionBuilder()
      .withUrl(url, options)
      .withAutomaticReconnect([0, 2000, 10000, 30000]) // 自定义重连策略
      .configureLogging(LogLevel.Information)
      .build()
  },

  // 启动连接
  async startConnection(connection) {
    try {
      await connection.start()
      console.log('SignalR 连接成功')
      return true
    } catch (err) {
      console.error('SignalR 连接失败:', err)
      return false
    }
  },

  // 关闭连接
  async stopConnection(connection) {
    if (connection) {
      await connection.stop()
      console.log('SignalR 连接已关闭')
    }
  }
}

3. 在 Vue 组件中使用

<script>
import signalR from '@/utils/signalR' // 导入工具类

export default {
  data() {
    return {
      connection: null,      // SignalR 连接实例
      message: '',           // 输入框绑定的消息
      messages: [],         // 接收到的消息列表
      hubUrl: 'https://your-api.com/chatHub' // Hub 地址
    }
  },
  mounted() {
    this.initializeConnection()
  },
  beforeUnmount() {
    // 组件销毁前关闭连接
    signalR.stopConnection(this.connection)
  },
  methods: {
    // 初始化连接
    async initializeConnection() {
      // 创建连接实例
      this.connection = signalR.createConnection(this.hubUrl, {
        accessTokenFactory: () => localStorage.getItem('token') // 身份验证(可选)
      })

      // 注册接收消息的回调
      this.connection.on('ReceiveMessage', (user, message) => {
        this.messages.push({ user, message })
      })

      // 启动连接
      const success = await signalR.startConnection(this.connection)
      if (!success) {
        alert('连接服务器失败,请检查网络')
      }

      // 监听连接关闭事件
      this.connection.onclose(() => {
        console.log('连接已断开')
      })
    },

    // 发送消息
    async sendMessage() {
      if (!this.message.trim()) return

      try {
        // 调用服务端 Hub 方法(假设方法名为 SendMessage)
        await this.connection.invoke('SendMessage', this.message)
        this.message = ''
      } catch (err) {
        console.error('发送消息失败:', err)
        alert('发送失败,请重试')
      }
    }
  }
}
</script>

<template>
  <div>
    <h2>聊天室</h2>
    <div class="message-list">
      <div v-for="(msg, index) in messages" :key="index">
        <strong>{{ msg.user }}:</strong> {{ msg.message }}
      </div>
    </div>
    <input v-model="message" @keyup.enter="sendMessage" placeholder="输入消息" />
    <button @click="sendMessage">发送</button>
  </div>
</template>

4. 服务端代码(C# ASP.NET Core 示例)

// Hub 类
public class ChatHub : Hub
{
    // 客户端调用此方法发送消息
    public async Task SendMessage(string message)
    {
        // 广播消息给所有客户端(方法名 ReceiveMessage 需与前端匹配)
        await Clients.All.SendAsync("ReceiveMessage", Context.User.Identity.Name, message);
    }
}

// Startup.cs 或 Program.cs 中配置
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ChatHub>("/chatHub");
});

关键注意事项

通过这个案例,你可以快速实现:

总结 

到此这篇关于前端vue中使用signalr的文章就介绍到这了,更多相关前端vue使用signalr内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文