Asp.NetCore+Microsoft.AspNetCore.SignalR先後端分離

一、新建WebApi 

  

 

二、安裝Microsoft.AspNetCore.SignalR

 

三、新建一個集線器和消息類

 

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; }
    }
}

四、配置Startup

 

五、新建html,併發布到iis

注: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>

六、效果圖

 

參考文檔https://docs.microsoft.com/en-us/aspnet/core/signalr/get-started?tabs=visual-studio&view=aspnetcore-2.1html

Github地址https://github.com/zrkcode/SignalR.git前端

相關文章
相關標籤/搜索