zoukankan      html  css  js  c++  java
  • SignalR客户端和服务端编写,winfrom端

    服务,必须以管理员的权限运行

    using Microsoft.AspNet.SignalR;
    using Microsoft.Owin;
    using Microsoft.Owin.Cors;
    using Owin;
    
    [assembly: OwinStartup(typeof(SignalRSever.Startup))]
    namespace SignalRSever
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                //// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
                ////设置可以跨域访问
                //app.UseCors (Microsoft.Owin.Cors.CorsOptions.AllowAll);
                ////映射到默认的管理
                ////var hubConfiguration = new HubConfiguration();
                ////hubConfiguration.EnableDetailedErrors = true;
                ////app.MapSignalR ("/signalr", hubConfiguration);
                //app.MapSignalR();
    
                app.Map("/signalr", map =>
                {
                    // Setup the CORS middleware to run before SignalR.
                    // By default this will allow all origins. You can 
                    // configure the set of origins and/or http verbs by
                    // providing a cors options with a different policy.
                    map.UseCors(CorsOptions.AllowAll);
    
                    var hubConfiguration = new HubConfiguration
                    {
                        EnableJSONP = true,
                        EnableJavaScriptProxies = true,
                        EnableDetailedErrors = true,
    
                        // You can enable JSONP by uncommenting line below.
                        // JSONP requests are insecure but some older browsers (and some
                        // versions of IE) require JSONP to work cross domain
                        // EnableJSONP = true
                    };
                    // Run the SignalR pipeline. We're not using MapSignalR
                    // since this branch already runs under the "/signalr"
                    // path.
                    //最大数据量限制取消
                    GlobalHost.Configuration.MaxIncomingWebSocketMessageSize = null;
                    map.RunSignalR(hubConfiguration);
                });
            }
        }
    }
    using System.Threading.Tasks;
    using Microsoft.AspNet.SignalR;
    using System.Drawing;
    using System.Collections.Generic;
    using System.Linq;
    using System.Diagnostics;
    
    namespace SignalRSever
    {
        public class MyHub : Hub
        {
            readonly IHubContext _hubContext;
    
            public MyHub() : base()
            {
                _hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
            }
    
            //Clients.All.Hello()   去调用所有连接上的客户端中hello()方法,即Hello() 是客户端中的方法
            public void Hello()
            {
                Clients.All.hello();
            }
    
            public void Send(string msg)
            {
                string name = "NiHao";
                Clients.All.SendMessage(msg);
            }
    
            //客户端连接上时,会进入到此方法中
            public override Task OnConnected()
            {
                Trace.WriteLine("客户端连接成功");
             
    return base.OnConnected(); } public override Task OnReconnected() { Trace.WriteLine("客户端重连中"); return base.OnReconnected(); } public override Task OnDisconnected(bool stopCalled) { return base.OnDisconnected(stopCalled); } } }
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Client;
    using Microsoft.Owin.Hosting;
    
    namespace SignalRSever
    {
        public partial class frmSever : Form
        {
            private IDisposable signalR { get; set; }
    
            public frmSever()
            {
                InitializeComponent();
            }
            IHubContext _myHubContext;
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    //开启服务
                    signalR = WebApp.Start<Startup>("http://127.0.0.1");
                }
                catch (Exception ex)
                {
                }
                _myHubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
                _myHubContext.Clients.All.Send( DateTime.Now.ToString("HH:mm:ss"));
            }
        }
    }

    客户端

    using Microsoft.AspNet.SignalR.Client;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {  
            public Form1()
            {
                InitializeComponent();
            }
            /// <summary>
            /// 连接代理对象
            /// </summary>
            private IHubProxy _proxy { get; set; }
            /// <summary>
            /// 连接对象
            /// </summary>
            private HubConnection _conn { get; set; }
            private async void button1_Click(object sender, EventArgs e)
            {
                string url = "http://127.0.0.1";
                 _conn = new HubConnection(url, true);
                _conn.Closed += HubConnection_Closed;
                _conn.Received += HubConnection_Received;
                _conn.Reconnected += HubConnection_Succeed;
                _conn.TransportConnectTimeout = new TimeSpan(3000);
                 _proxy = _conn.CreateHubProxy("MyHub");
    
               
    
                //定义客户端的方法sendMessage()(有两个string类型的参数,当服务端调用sendMessage,需要传入2个string类型参数),以这种格式定义方法服务端才能去调用
                //接收实时信息
                _proxy.On<string>("SendMessage", DealMessage);
    
                await _conn.Start();
                Console.ReadLine();
            }
    
            private void HubConnection_Succeed()
            {
                
            }
    
            private void HubConnection_Received(string obj)
            {
                //响应结果
            }
    
            private void HubConnection_Closed()
            {
               //断开结果
            }
    
            private static void DealMessage(string objId)
            {
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                _proxy.Invoke("Send", "测试测试");
            }
        }
    }
  • 相关阅读:
    [Codeforces Round #498 (Div. 3)] -F. Xor-Paths (折半搜索)
    Best Reward [HDU
    [Educational Codeforces Round 72] A. Creating a Character (简单数学)
    [Codeforces Round #624 (Div. 3)] -E. Construct the Binary Tree (构造二叉树)
    [Codeforces Round #626 (Div. 2, based on Moscow Open Olympiad in Informatics)] -D. Present(异或性质,按位拆分,双指针)
    [Codeforces Round #626 (Div. 2, based on Moscow Open Olympiad in Informatics)] -D. Present(异或性质,按位拆分,树桩数组)
    [Educational Codeforces Round 83 ] E. Array Shrinking
    [AtCoder Beginner Contest 158]
    [CodeCraft-20 (Div. 2)]- E. Team Building (状压DP)
    HDU 3308 LCIS (线段树区间合并)
  • 原文地址:https://www.cnblogs.com/weifeng123/p/13453844.html
Copyright © 2011-2022 走看看