SignalR provides an API for creating server-to-client remote procedure calls (RPC). The clients can be JavaScript, .NET, or Java functions. Here are some of the main benefits to use SignalR as push architecture for real time applications.
- Handles connection management automatically.
- automatically chooses the best transport method that is within the capabilities of the server and client. (WebSocket, Server Sent Event, and Long Poll)
- Sends messages to all connected clients simultaneously. For example, a chat room.
- Sends messages to specific clients or groups of clients.
- Scales to handle increasing traffic.
The SignalR server library is included in the ASP.NET Core 3.1 shared framework. The JavaScript client library isn't automatically included in the project.
In Solution Explorer, right-click wwwroot/js/ folder, and select Add Client-Side Library. If you don't see it in the context menu, please check if you have VS extension Microsoft Library Manager.
Only select signalr.js and signalr.min.js.
After this you can create JS client now. Here is an example of JS client.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | "use strict"; var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build(); //Disable send button until connection is established document.getElementById("sendButton").disabled = true; connection.on("ReceiveMessage", function (user, message) { var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); var encodedMsg = user + " says " + msg; var li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); connection.start().then(function () { document.getElementById("sendButton").disabled = false; }).catch(function (err) { return console.error(err.toString()); }); document.getElementById("sendButton").addEventListener("click", function (event) { var user = document.getElementById("userInput").value; var message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); }); |
For more details to use SignalR in ASP.NET Core 3.1, please refer to the link below.
No comments:
Post a Comment