学习使用SignalR

1、创建空白的控制台程序

2、添加两个NuGet包(Microsoft.AspNet.SignalR.SelfHost、Microsoft.Owin.Cors、Topshelf)Topshelf用于快捷创建windows服务

3、添加Myservice服务类

using Microsoft.AspNet.SignalR.Hosting;
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCode_Framework_ConsoleSignalR
{
    public class MyService
    {
        private IDisposable SignalR { get; set; }
        private string SignalRUrl = string.Empty;
        public MyService()
        {
            SignalRUrl = "http://127.0.0.1:1010";
            Console.WriteLine("获取配置:" + SignalRUrl);
        }

        public bool Start()
        {
            try
            {
                Console.WriteLine("事实消息服务运行在:" + SignalRUrl);
                SignalR = WebApp.Start(SignalRUrl);
                return true;
            }
            catch
            {
                return false;
            }

        }

        public bool Stop()
        {
            if (SignalR != null)
            {
                SignalR.Dispose();
            }
            return true;
        }
    }
}

4、设置Program文件中Main类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using Topshelf;
namespace BCode_Framework_ConsoleSignalR
{
    class Program
    {
        static void Main()
        {
            HostFactory.Run(x => {
                //设置服务窗口
                x.Service<MyService>(sc =>
                {
                    sc.ConstructUsing(service => new MyService());
                    sc.WhenStarted(service => service.Start());
                    sc.WhenStopped(service => service.Stop());
                });
                x.SetServiceName("CheckService");//服务名称
                x.SetDescription("Check");//服务描述
                x.SetDisplayName("Check Service");//服务显示的名称
                x.RunAsLocalSystem();//以本地系统账户启动服务
            });



            #region 为了方便调试
            StartOptions options = new StartOptions();
            //服务器Url设置
            options.Urls.Add("http://127.0.0.1:1010");
            //Server实现类库设置
            options.ServerFactory = "Microsoft.Owin.Host.HttpListener";
            //以当前的Options和Startup启动Server
            using (WebApp.Start(options))
            {
                Console.WriteLine("Owin Host/Server started,press enter to exit it...");
                //显示启动信息,通过ReadLine驻留当前进程
                Console.ReadLine();
            }//Server在Dispose中关闭
            #endregion


        }
    }
}

5、创建SignalR集线器类 重写了一个连接方法和创建一个客户端方法

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Threading.Tasks;
namespace BCode_Framework_ConsoleSignalR.Hubs
{
    //定义客户端调用服务端方法的名称,如果没有定义注意客户端会自动把服务端方法的首字母改为小写
    [HubName("serviceMonitorHub")]
    public class ServiceMonitorHub:Hub
    {
        //当客户端与服务器建立连接后执行的方法
        public override Task OnConnected()
        {
            //获取客户端ID
            Console.WriteLine("{0}已连接", Context.ConnectionId);
            //服务端往客户端发送数据ServerSendData方法为客户端定义的方法
            Clients.Client(Context.ConnectionId).ServerSendData("服务端与客户端:" + Context.ConnectionId + "成功建立连接!");
            return base.OnConnected();
        }
        //客户端执行服务器端的方法
        [HubMethodName("ClickSendData")]
        public void ClickSendData(string msg)
        {
            Console.WriteLine("接收到客户端" + Context.ConnectionId + "发送的数据:" + msg);
        }
    }
}

6、添加Startup启动类

using Microsoft.Owin.Cors;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCode_Framework_ConsoleSignalR
{
    class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
        }
    }
}

 

7、客户端调用

web端引用NuGet包(Microsoft.AspNet.SignalR.JS)

<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<script src="http:127.0.0.1:1010/SignalR/Hubs"></script>
<div>
    <input id="txt_value" type="text" />
    <input id="btn_send" type="button" value="发送" />
    <label id="lbl_msg"></label>
</div>
<script>
    var KeyValue = "";
    var app = null;
    var Connectioned = false;
    $(function () {
        if (!Connectioned) {
            $.connection.hub.url = "http:127.0.0.1:1010/SignalR/Hubs";
            app = $.connection.serviceMonitorHub;
        }
        if (app != null) {
            app.client.ServerSendData = function (msg) {
                $("#lbl_msg").append("<br/>" + msg);
            }
            $.connection.hub.start()
                .done(function () {

                    $('#btn_send').click(function () {
                         connected = true;
                    console.log('Now connected, connection ID=' + $.connection.hub.id);
                    app.server.ClickSendData($("#txt_value").val());
                    })

                   
                })
                .fail(function () {
                    console.log('Not fount connect');
                })
        }

    })
</script>

8、测试结果

 

猜你喜欢

转载自www.cnblogs.com/heibai-ma/p/11327771.html