2021-10-18

- 服务器端(WinForm)

1.创建WinForm程序 SignalRService
在这里插入图片描述

  1. 添加新项-OWIN Startup类
    在这里插入图片描述

  2. 添加GIT包引用
    安装两个NuGet包
    Microsoft.Owin.SelfHost
    Microsoft.AspNet.SignalR.SelfHost

  3. 创建MoveTextHub类,需要继承于: Hub。在类上面添加[HubName(“getMessage”)]Hub的别名,方便前台调用

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

//Hub的别名,方便前台调用
//[HubName("getMessage")]
public class MyHub : Hub
{
    /// <summary>
    /// 编写发送信息的方法
    /// </summary>
    /// <param name="name"></param>
    /// <param name="message"></param>
    public void Send(string name, string message)
    {
        //调用所有客户注册的本地的JS方法(addMessage)
        Clients.All.addMessage(name, message);
    }
} 
  1. 设置刚刚创建的Startup
    安装一个GetHub包
    Microsoft.Owin.Cors
    设置刚刚创建的Startup
using Microsoft.Owin.Cors;
using Owin;

namespace SignalRService
{
    public class Startup1
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
        }
    }
}
  1. 主窗体,两个按钮,一个启动,一个停止,还有一个文本框,用于显示输出信息。
    代码如下:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Owin.Hosting;

namespace SignalRService
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public IDisposable SignalR { get; set; }
        private const string ServerUri = "http://localhost:8888"; // SignalR服务地址

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnStart_Click(object sender, EventArgs e)
        {
            BtnStart.Enabled = false;

            WriteToConsole("正在启动服务...");
            Task.Run(() => { BtnStart.Enabled = !StartServer(); }); // 异步启动SignalR服务
             
            //Task.Run(() => StartServer()); // 异步启动SignalR服务
            //Task.Run(() =>
            //{
            //    BtnStart.Enabled = !StartServer();
            //bool flag = StartServer();
            //BtnStart.Invoke(new Action<bool>((f) => BtnStart.Enabled = !f), flag);

            // }); // 异步启动SignalR服务

            //BtnStart.Enabled = !StartServer();
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnStop_Click(object sender, EventArgs e)
        {
            SignalR.Dispose();
            Close();
        }


        /// <summary>
        /// 启动SignalR服务,将SignalR服务寄宿在WPF程序中
        /// </summary>
        private bool StartServer()
        {
            try
            {
                SignalR = WebApp.Start(ServerUri);  // 启动SignalR服务
            }
            catch (Exception ex)
            {
                WriteToConsole(ex.Message);
                return false;
            }

            WriteToConsole("服务已经成功启动,地址为:" + ServerUri);
            return true;
        }

        private delegate void WriteToConsoleDe(string msg);
        /// <summary>
        /// 将消息添加到消息列表中
        /// </summary>
        /// <param name="message"></param>
        public void WriteToConsole(string message)
        {
            if (TxtConsole.InvokeRequired)
            {
                TxtConsole.Invoke(new Action<string>((string msg) => TxtConsole.AppendText(message + Environment.NewLine)), message);
                return;
            }

            TxtConsole.AppendText(message + Environment.NewLine);
        }



    }
}
  • 客户端(HTML)
  1. 创建Web空程序 SignalRWebApplication

  2. 添加GIT包

Microsoft.AspNet.SignalR.JavaScript.Client

  1. 添加HTML页面,命名为:SendMessage.html

  2. SendMessage代码如下

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="http://localhost:8080/signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            //Set the hubs URL for the connection
            $.connection.hub.url = "http://localhost:8080/signalr";

            // Declare a proxy to reference the hub.
            var chat = $.connection.myHub;

            // Create a function that the hub can call to broadcast messages.
            chat.client.addMessage = function (name, message) {
                // Html encode display name and message.
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html

源码下载:https://pan.baidu.com/s/1bpayjT1
转载于:https://www.cnblogs.com/ypeuee/p/8184786.html
相关资源:SignalR2.0Winform版_signalrwinform,signalrwinfrom-C#代码类…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值