Asp.NET websocket,Asp.NET MVC 使用 SignalR 实时更新前端页面数据

目标:数据库数据改变时,实时更新到页面数据(例如  车辆进出识别车牌号后写入数据库信息,同时更新用户浏览的前端页面车辆进出信息列表)

要点:1、前端加载数据时向后台请求SignalR 接口即发送请求消息  建立连接状态;2、数据更新后  在后台再次调用发送消息的接口  推送到前端页面消息

更新前:

更新后:

@{
    ViewBag.Title = "Index";
}
@{
    Layout = null;
}

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>websocket</title>
</head>
<body>
    <form action="/" method="post">
        @*<textarea rows="10" cols="300" id="msg"></textarea>*@
        <button id="btn_send" type="button">更新数据</button>
    </form>
    <div id="chatContent"></div>

    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. 注意一定别忘记写这句,signalr生成的脚本都在这-->
    <script src="~/signalr/hubs"></script>
    <script src="~/Scripts/core/talk.js"></script>
</body>
</html>
View Code
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalR_Chat.DbHelp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace SignalR_Chat.Hubs
{
    [HubName("chat")]//使用小写,试过使用大写,但是在html页会出错
    public class ChatHub : Hub
    {
        public void SendMessage()
        {
            string msg = string.Empty, message=string.Empty;
            DataTable dt= DbOp.GetData("SELECT ui.UserName FROM UserInfo AS ui WHERE ui.Id='F58500C9-EE07-43B0-BE47-002B1C219306'",out msg);
            message = dt.Rows[0]["UserName"].ToString();
            //Clients.All.addNewMessageToPage(message);
            //因为在后台调用,所以要这样,否则会出错,提示Using a Hub instance not created by the HubPipeline is unsupported</pre> 
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            hubContext.Clients.All.addNewMessageToPage(message);
        }

    }
}
View Code
   public ActionResult UpdateData()
        {
            DbOp.UpdateRow("UPDATE UserInfo SET UserName='aaa' WHERE Id='F58500C9-EE07-43B0-BE47-002B1C219306'");
            new ChatHub().SendMessage();
            return null;
        }
View Code
@{
    ViewBag.Title = "Index";
}
@{
    Layout = null;
}

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>websocket</title>
</head>
<body>
    <form action="/" method="post">
        @*<textarea rows="10" cols="300" id="msg"></textarea>*@
        <button id="btn_send" type="button">更新数据</button>
    </form>
    <div id="chatContent"></div>

    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. 注意一定别忘记写这句,signalr生成的脚本都在这-->
    <script src="~/signalr/hubs"></script>
    <script src="~/Scripts/core/talk.js"></script>
</body>
</html>
View Code
原文地址:https://www.cnblogs.com/cxxtreasure/p/13584185.html