SignalR示例

做了个SignalR的示例,官方的示例服务是宿主在asp.net core的。

aspnet/SignalR-samples: Samples for ASP.NET Core SignalR (github.com)

SignalR/samples/SignalRSamples at master · aspnet/SignalR (github.com)

参考网上的文章做了个宿主在winform上的示例,几点总结记录一下:

1. winform上使用的是owin提供网站服务,但owin不支持.net core,只能用.net framework。最先用.net 6.0启动服务一直报错。可直接Nuget安装 Microsoft.AspNet.SignalR.SelfHost.

2. 客户端连接要用new HubConnection的方式,用官网的winform示例会一直报连接中断。

3. 不同客户端可通过CreateHubProxy里指定不同的Hub名称实现类似Topic的功能。

4. 服务端可通过 GlobalHost.ConnectionManager.GetHubContext<ChatHub>();取得Hub上下文然后发送消息。

5. 获得主窗体和跨线程处理以及代理方法的写法,winform 和 wpf 有区别。WPF是 Application.Current.Dispatcher.Invoke,在Winform里Application.OpenForms[0].Invoke

C# WinForm获得主窗体——如何判断哪个是主窗体 - 白い - 博客园 (cnblogs.com)

服务端程序后台代码:

public partial class Form1 : Form
    {
        string ServerUri = "http://localhost:8011/signalr";
        private IDisposable SignalR { get; set; }

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ServerUri=txtSvrUri.Text;
            StartServer();
        }

        /// <summary>
        /// 启动SignalR服务,将SignalR服务寄宿在WPF程序中
        /// </summary>
        private void StartServer()
        {
            try
            {
                SignalR = WebApp.Start(ServerUri);  // 启动SignalR服务
            }
            catch (TargetInvocationException)
            {
                LogMsg("一个服务已经运行在:" + ServerUri);
                // Dispatcher回调来设置UI控件状态
                //this.Invoke(new Action(()=> btnStart.Enabled = true));
                return;
            }

            this.Invoke(new Action(() => btnStart.Enabled = false));
            this.Invoke(new Action(() => btnStop.Enabled = true));
            LogMsg("服务已经成功启动,地址为:" + ServerUri);
        }

        public delegate void UpdateForm_dl();

        public void LogMsg(string msg)
        {
            richTxtMsg.AppendText($"{msg}{Environment.NewLine}");
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            hubContext.Clients.All.SendClose("服务端已关闭");

            SignalR.Dispose();
            LogMsg("服务已经成功停止,地址为:" + ServerUri);
            this.Invoke(new Action(() => btnStart.Enabled = true));
            this.Invoke(new Action(() => btnStop.Enabled = false));
        }
    }

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
            // 允许CORS跨域
            //app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
        }
    }

    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            Clients.All.AddMessage(name, message);
        }

        public override Task OnConnected()
        {
            //
            Application.OpenForms[0].Invoke(new Action(() =>
                ((Form1)Application.OpenForms[0]).LogMsg("客户端连接,连接ID是: " + Context.ConnectionId)));

            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            Application.OpenForms[0].Invoke(new Action(() =>
               ((Form1)Application.OpenForms[0]).LogMsg("客户端断开连接,连接ID是: " + Context.ConnectionId)));

            return base.OnDisconnected(true);
        }
    }

    public class ChatHub2 : Hub
    {
        public void Send(string name, string message)
        {
            Clients.All.AddMessage(name, message);
        }

        public override Task OnConnected()
        {
            //
            Application.OpenForms[0].Invoke(new Action(() =>
                ((Form1)Application.OpenForms[0]).LogMsg("客户端连接2,连接ID是: " + Context.ConnectionId)));

            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            Application.OpenForms[0].Invoke(new Action(() =>
               ((Form1)Application.OpenForms[0]).LogMsg("客户端断开连接2,连接ID是: " + Context.ConnectionId)));

            return base.OnDisconnected(true);
        }
    }

客户端后台代码:

public partial class Form1 : Form
    {
        public IHubProxy HubProxy { get; set; }
        string ServerUri = "http://localhost:8011/signalr";
        public HubConnection Connection { get; set; }


        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            ServerUri = txtSvrUri.Text;
            ConnectAsync();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            // 通过代理来调用服务端的Send方法
            // 服务端Send方法再调用客户端的AddMessage方法将消息输出到消息框中
            HubProxy.Invoke("Send", GenerateRandomName(4), txtSend.Text.Trim());

            txtSend.Text = String.Empty;
            txtSend.Focus();
        }

        public void LogMsg(string msg)
        {
            richTxtMsg.AppendText($"{msg}{Environment.NewLine}");
        }

        private async void ConnectAsync()
        {
            Connection = new HubConnection(ServerUri);
            Connection.Closed += Connection_Closed;
            Connection.Received += Connection_Received;

            // 创建一个集线器代理对象
            HubProxy = Connection.CreateHubProxy(txtTopic.Text);

            // 供服务端调用,将消息输出到消息列表框中
            HubProxy.On<string, string>("AddMessage", (name, message) =>
                 this.Invoke(new Action(() =>
                    LogMsg(String.Format("{0}: {1}", name, message)))
                ));

            try
            {
                await Connection.Start();
            }
            catch (HttpRequestException)
            {
                // 连接失败
                return;
            }

            // 显示聊天控件
            //ChatPanel.Visibility = Visibility.Visible;
            btnSend.Enabled = true;
            txtSend.Focus();
            LogMsg("连上服务:" + ServerUri);
        }

        private void Connection_Closed()
        {
            this.Invoke(new Action(() =>
                    LogMsg("connection closed"))
                );
            
        }

        private void Connection_Received(string data)
        {
            this.Invoke(new Action(() =>
                    LogMsg($"recived data:{data}"))
                );

        }

        public string GenerateRandomName(int length)
        {
            var newRandom = new System.Text.StringBuilder(62);
            var rd = new Random();
            for (var i = 0; i < length; i++)
            {
                newRandom.Append(Constant[rd.Next(62)]);
            }
            return newRandom.ToString();
        }

        private readonly char[] Constant =
        {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
            'W', 'X', 'Y', 'Z'
        };

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            Connection.Stop();
        }
    }

[Asp.net 开发系列之SignalR篇]专题一:Asp.net SignalR快速入门 - Learning hard - 博客园 (cnblogs.com)

基于SignalR的服务端和客户端通讯处理_独星的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值