步骤:

  第一步,创建项目(MVC版本的),然后再创建SignalR

SignalR 的使用

SignalR 的使用

第二步:引入JS和引入 <script src="~/signalr/hubs"></script> 尤其重要;

第三步:在控制器中创建方法:

第四步:  在Startup类别中配置

       public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();
        }

 

源码:

前端:

 <script src="~/Scripts/jquery-3.4.1.js"></script>
 <script src="~/Scripts/jquery.signalR-2.2.2.js"></script>
 <script src="~/signalr/hubs"></script>
 <textarea id="msg">

 </textarea>
<button οnclick="Send()">
    发送
</button>
<script type="text/javascript">

    //$.connection.hub.url = "http://localhost:8889/signalr";
    var chat = $.connection.myHub;
    chat.client.getMessage = function (msg) {
        //向页面添加消息
        alert(msg);
    }
    // 开始连接服务器
    $.connection.hub.start().done(function () {
        console.log("链接成功");
    });

    function Send() {

        $.ajax({
            url: "/Home/Msg?msg="+$("#msg").val()


        });
        
    }
</script>

<div>
    <h5>消息提示</h5>
</div>
 

后端:

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Message.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public string Msg(string msg ) {
            try
            {
                IHubContext _hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
                _hubContext.Clients.All.getMessage(msg);
                return "发送成功";
            }
            catch (Exception ex)
            {

                return ex.Message.ToString();
            }
          
            
        }
    }
}

 

在startup中配置

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Message.Startup))]

namespace Message
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();
        }
    }
}
 

 

 

相关文章:

  • 2021-07-30
  • 2022-12-23
  • 2021-08-01
  • 2022-02-09
  • 2019-09-18
  • 2019-09-15
  • 2021-06-12
  • 2021-12-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-17
  • 2021-12-23
相关资源
相似解决方案