繼上篇文章 AspNetCore Web API專案使用SignalR之用法,這次要在Vue專案裡使用SignalR來做後續的動作
首先在Vue3專案裡下命令安裝:
npm install @microsoft/signalr
引用@microsoft/signalr
import * as signalR from '@microsoft/signalr'
接著寫function如下:
/**
* 從SignalR通道接收訊息
*/
receiveFromSignalR() {
let connection = new signalR.HubConnectionBuilder()
.withUrl(`${window._config.webApi_URL}/windowsServiceHub`)
.build()
try {
connection.start()
console.log('signalR connected')
connection.on('SendWindowsServiceStatus', (message) => {
console.log('SendWindowsServiceStatus', message)
if (message === true || message === 'true') {
this.windowsServiceStatus = true
} else {
console.log(`windowsServiceStatus close`)
this.windowsServiceStatus = false
}
})
} catch (error) {
console.log('signalR error', error)
}
}
然後等來自windows service或windows console專案等等的觸發即可達到雙向溝通,參閱 AspNetCore Web API專案使用SignalR之用法