1. 程式人生 > 實用技巧 >SignalR客戶端和服務端編寫,winfrom端

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(name, 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>("AddMessage", 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", "測試測試");
        }
    }
}