首页 > 代码库 > signalR

signalR

1.添加signalR包

2.添加Startup类

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

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

namespace signalR
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            //注册signalr/hubs
            app.MapSignalR();
        }
    }
}

 3.添加MyHub类

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

namespace signalR
{
    public class MyHub : Hub
    {
        public void Hello(string message)
        {
            Clients.All.hello(message);
        }
    }
}

 4.前台js引用并实现

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://www.mamicode.com/Scripts/jquery-1.6.4.min.js"></script>
    <script src="http://www.mamicode.com/Scripts/jquery.signalR-2.2.2.min.js"></script>
    <script src="http://www.mamicode.com/signalr/hubs"></script>
    <script>
        $(function () {
            var hellohub = $.connection.myHub;
            hellohub.client.hello = function (message) {
                $("#text").append("<p>" + message + "</P>");
            };
            $.connection.hub.start().done(function () {
                $("#send").click(function () {
                    hellohub.server.hello("testmessage");
                })
            });
        })        
    </script>
</head>
<body>
    <input id="send" type="button" value="http://www.mamicode.com/send" />
    <div id="text"></div>
</body>
</html>

 5.后台调用代码

Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<MyHub>().Clients.All.hello(content);

 

signalR