前端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();
參數(shù)說明
在使用 SignalR 的 HubConnectionBuilder 時,可以通過鏈式方法配置連接的各個參數(shù)。以下是完整的參數(shù)配置寫法和說明:
const connection = new signalR.HubConnectionBuilder()
// 必填:設置 Hub 的 URL
.withUrl(url, options)
// 可選:配置日志
.configureLogging(logging)
// 可選:配置自動重連
.withAutomaticReconnect(retryPolicy)
// 可選:配置自定義 HTTP 客戶端
.withHubProtocol(protocol)
// 構(gòu)建連接對象
.build();
1. withUrl
- 作用:設置 SignalR Hub 的 URL 和連接選項。
- 參數(shù):
.withUrl(url: string, options?: IHttpConnectionOptions).withUrl("https://example.com/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpConnectionOptions.LongPolling, // 自定義傳輸方式(默認為自動選擇) accessTokenFactory: () => "your-access-token", // 身份驗證 Token(如 JWT) httpClient: customHttpClient, // 自定義 HTTP 客戶端(如修改超時時間) skipNegotiation: true, // 跳過協(xié)商步驟(僅適用于 WebSocket) headers: { "X-Custom-Header": "value" }, // 自定義請求頭 // WebSocket 配置 websocket: { // 自定義 WebSocket 構(gòu)造函數(shù)(如代理) constructor: CustomWebSocket, }, // 是否使用默認的 `fetch` API(默認為 true) useDefaultFetch: false, })
2. configureLogging
- 作用:配置日志級別或自定義日志記錄器。
- 參數(shù):
.configureLogging(logging: LogLevel | ILogger) - 示例:
// 簡單配置日志級別 .configureLogging(signalR.LogLevel.Information) // 自定義日志記錄器 .configureLogging({ log(logLevel, message) { console.log(`[SignalR] ${logLevel}: ${message}`); } })
3. withAutomaticReconnect
- 作用:配置自動重連策略。
- 參數(shù):
.withAutomaticReconnect(retryPolicy?: RetryPolicy)// 默認策略:重試 0次、3次、10次、30次 后停止 .withAutomaticReconnect() // 自定義重試間隔數(shù)組(單位:毫秒) .withAutomaticReconnect([0, 2000, 5000, 10000, 30000]) // 高級策略:實現(xiàn) `RetryPolicy` 接口 .withAutomaticReconnect({ nextRetryDelayInMilliseconds(retryContext) { if (retryContext.elapsedMilliseconds < 60000) { return Math.random() * 1000; // 隨機延遲 <1s } return null; // 停止重連 } })
4. withHubProtocol
- 作用:設置消息協(xié)議(默認為 JSON)。
- 參數(shù):
.withHubProtocol(protocol: IHubProtocol) - 示例:
// 使用 MessagePack 二進制協(xié)議 .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol()) // 自定義協(xié)議(需實現(xiàn) IHubProtocol)
5. build
- 作用:生成最終的
HubConnection實例。 - 示例:
.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)
withCredentials:跨域請求攜帶 Cookie。.withUrl(url, { withCredentials: true })timeout:設置單個 HTTP 請求超時時間。.withUrl(url, { timeout: 15000 }) // 15秒
根據(jù)實際需求選擇配置項,確保兼容 SignalR 客戶端庫的版本。
三、啟動連接
啟動連接是指讓前端與SignalR Hub建立實際的連接。
connection.start().then(() => {
console.log("SignalR Connected.");
}).catch(err => {
console.error(err.toString());
});
四、定義客戶端方法(客戶端接收服務端信息)
客戶端方法是指SignalR Hub調(diào)用時客戶端執(zhí)行的函數(shù)。通過這些方法,前端可以響應來自服務器的實時通知。
// 實時接收服務端信息(服務端-->客戶端)
connection.on('監(jiān)聽后端命名的方法A返回的數(shù)據(jù):名稱一般和invoke配套',(message) => {
console.log('接受的信息Info message:', message);
// 做一些賦值操作,把后端傳來的數(shù)據(jù)渲染到頁面
});
// 例:
connection.on("ReceiveMessage", (user, message) => {
const msg = `${user}: ${message}`;
const li = document.createElement("li");
li.textContent = msg;
document.getElementById("messagesList").appendChild(li);
});
五、發(fā)送消息到服務器
前端可以通過調(diào)用SignalR Hub的方法來發(fā)送消息到服務器。通常,這些方法是用戶操作(如點擊按鈕)觸發(fā)的。
// 客戶端與服務端進行溝通(客戶端-->服務端),客戶端調(diào)取后端的方法進行通訊,后端返回信息
connection.invoke("后端命名的方法A", "一些后端需要的變量根據(jù)自己需求填寫")
// 例:
connection.invoke('SendData', 'Hello, SignalR!');
六、實際應用場景
實時聊天應用
使用SignalR最常見的場景之一就是實時聊天應用。通過SignalR,可以實現(xiàn)客戶端之間的實時消息傳遞。實時數(shù)據(jù)更新
SignalR也可以用于實時數(shù)據(jù)更新,如股票行情、體育比賽比分等。這些應用需要頻繁地從服務器獲取最新數(shù)據(jù),并實時更新到前端界面。通知系統(tǒng)
在一些應用中,當有新的事件發(fā)生時,需要實時通知用戶。例如,在電商平臺中,當有新的訂單或者庫存變化時,需要及時通知管理員。
七、完整案例
以下是一個在 Vue 3 中使用 SignalR 實現(xiàn)連接、發(fā)送和接收數(shù)據(jù)的完整案例,包含詳細注釋和關鍵配置:
1. 安裝依賴
npm install @microsoft/signalr
2. 創(chuàng)建 SignalR 工具類(可選)
在 src/utils/signalR.js 中封裝連接邏輯:
import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr'
export default {
// 創(chuàng)建連接
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() {
// 創(chuàng)建連接實例
this.connection = signalR.createConnection(this.hubUrl, {
accessTokenFactory: () => localStorage.getItem('token') // 身份驗證(可選)
})
// 注冊接收消息的回調(diào)
this.connection.on('ReceiveMessage', (user, message) => {
this.messages.push({ user, message })
})
// 啟動連接
const success = await signalR.startConnection(this.connection)
if (!success) {
alert('連接服務器失敗,請檢查網(wǎng)絡')
}
// 監(jiān)聽連接關閉事件
this.connection.onclose(() => {
console.log('連接已斷開')
})
},
// 發(fā)送消息
async sendMessage() {
if (!this.message.trim()) return
try {
// 調(diào)用服務端 Hub 方法(假設方法名為 SendMessage)
await this.connection.invoke('SendMessage', this.message)
this.message = ''
} catch (err) {
console.error('發(fā)送消息失敗:', err)
alert('發(fā)送失敗,請重試')
}
}
}
}
</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">發(fā)送</button>
</div>
</template>
4. 服務端代碼(C# ASP.NET Core 示例)
// Hub 類
public class ChatHub : Hub
{
// 客戶端調(diào)用此方法發(fā)送消息
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");
});
關鍵注意事項
跨域問題:確保服務端啟用 CORS:
services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()));身份驗證:如果使用 JWT,需在
withUrl配置中傳遞 Token:.withUrl(this.hubUrl, { accessTokenFactory: () => localStorage.getItem('token') })協(xié)議兼容:默認使用 JSON 協(xié)議,如需二進制優(yōu)化可切換為 MessagePack:
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack' this.connection = new HubConnectionBuilder() .withHubProtocol(new MessagePackHubProtocol())錯誤處理:建議全局監(jiān)聽錯誤:
this.connection.onreconnecting((error) => { console.log('正在嘗試重新連接...', error) })性能優(yōu)化:在頻繁通信場景下,建議使用 WebSocket 傳輸(需服務端支持):
.withUrl(url, { transport: HttpTransportType.WebSockets })
通過這個案例,你可以快速實現(xiàn):
- SignalR 長連接管理
- 消息的發(fā)送和實時接收
- 自動重連和錯誤處理
- 與 Vue 3 生命周期的無縫集成
總結(jié)
到此這篇關于前端vue中使用signalr的文章就介紹到這了,更多相關前端vue使用signalr內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用 vue 實例更好的監(jiān)聽事件及vue實例的方法
這篇文章主要介紹了使用 vue 實例更好的監(jiān)聽事件及vue實例的方法,介紹了一種新增 vue 實例的方法,單獨監(jiān)聽事件,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04

