ASP.NET SignalR 是為 ASP.NET 開發人員提供的一個庫,可以簡化開發人員將實時 Web 功能添加到應用程序的過程。實時 Web 功能是指這樣一種功能:當所連接的客戶端變得可用時服務器代碼可以立即向其推送內容,而不是讓服務器等待客戶端請求新的數據。
下面是簡單的demo;參考(https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-3.0)
一下代碼運行的結果是:
前端通過(CarPositionChanged)像服務器發送一段數據,服務器接收后,再通過(RegisterClient)給前端推送相應的數據,整個過程中頁面不會刷新
document.addEventListener('DOMContentLoaded', function () {
var messageInput = document.getElementById('message');
// Get the user name and store it to prepend to messages.
var name = prompt('Enter your name:', '');
// Set initial focus to message input box.
messageInput.focus();
// 開始一個鏈接
var connection = new signalR.HubConnectionBuilder()
.withUrl('http://192.168.1.156:5000/privatecar')
.build();
connection.qs = { 'orderId' : '12346579' };
// 服務器推送過來的信息
connection.on('RegisterClient', function (name, message) {
// Html encode display name and message.
console.log(name)
});
// Transport fallback functionality is now built into start.
connection.start()
.then(function () {
console.log('connection started');
document.getElementById('sendmessage').addEventListener('click', function (event) {
// 發送到服務器
connection.invoke('CarPositionChanged', name, messageInput.value);
// Clear text box and reset focus for next comment.
messageInput.value = '';
messageInput.focus();
event.preventDefault();
});
})
.catch(error => {
console.error(error.message);
});
});
