using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace WebApi.Chat { public class ChatHub : Hub { //SendMsg用於前端調用 public Task SendMsg(ChatMessageInfo info) { //在客戶端實現此處的Show方法 return Clients.All.SendAsync("Show", info.UserName + ":" + info.Message); } } }
namespace WebApi.Chat { public class ChatMessageInfo { public string UserName { get; set; } public string Message { get; set; } } }
注:signalr.min.js不依賴jquery,此處只是方便編碼,經過如下兩個命令在node_modules\ @aspnet\signalr\dist\browser中得到signalr的js文件。 javascript
npm init -y
npm install @aspnet/signalr
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <input type="text" id="userid" placeholder="Enter user name" /> <br> <input type="text" id="message" placeholder="Enter sned message" /> <input type="button" id="btnSend" value="Send" /> <ul id="msglist"></ul> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="signalr.min.js"></script> <script> $(function () { //服務地址 let hubUrl = 'http://localhost:50432/chathub'; let httpConnection = new signalR.HttpConnection(hubUrl); let hubConnection = new signalR.HubConnection(httpConnection); $("#btnSend").click(function () { //新建對象 let obj = new Object(); obj.UserName = $('#userid').val(); obj.Message = $('#message').val(); //調用服務器方法 hubConnection.invoke('SendMsg', obj); }); //服務器回調方法 hubConnection.on('Show', data => { $('#msglist').append($('<li>').text(data)); }); hubConnection.start(); }); </script> </body> </html>
Github地址:https://github.com/zrkcode/SignalR.git前端