【问题标题】:how to setup a C# winforms application to host SignalR Hubs?如何设置 C# winforms 应用程序来托管 SignalR 集线器?
【发布时间】:2012-07-20 01:59:23
【问题描述】:

我已阅读 SignalR 文档并观看了一些视频,但是我无法让 SignalR 在 winforms 应用程序中托管。

我尝试使用 SignalR wiki 上的源代码:https://github.com/SignalR/SignalR/wiki/Self-host

如果您查看“完整示例 - 集线器”,“服务器”变量是什么?我不明白这是如何工作的或如何将其转换为 C#。根据 wiki “默认的 SelfHost 实现建立在 HttpListener 之上,可以托管在任何类型的应用程序(控制台、Windows 服务等)中。”

我想在 C# 中托管 SignalR,并在 asp.net 中使用它。谁能帮我解释一下?

【问题讨论】:

    标签: c# winforms signalr


    【解决方案1】:

    Wiki 中的示例运行良好。

    请使用 NuGet(包管理器控制台)安装 SignalR.Hosting.Self

    安装包 SignalR.Hosting.Self

    Server 位于 SignalR.Hosting.Self 命名空间中。

    样本

    控制台应用程序

    using System;
    
    namespace MyConsoleApplication
    {
        static class Program
        {
            static void Main(string[] args)
            {
                string url = "http://localhost:8081/";
                var server = new SignalR.Hosting.Self.Server(url);
    
                // Map the default hub url (/signalr)
                server.MapHubs();
    
                // Start the server
                server.Start();
    
                Console.WriteLine("Server running on {0}", url);
    
                // Keep going until somebody hits 'x'
                while (true)
                {
                    ConsoleKeyInfo ki = Console.ReadKey(true);
                    if (ki.Key == ConsoleKey.X)
                    {
                        break;
                    }
                }
            }
    
            public class MyHub : SignalR.Hubs.Hub
            {
                public void Send(string message)
                {
                    Clients.addMessage(message);
                }
            }
        }
    }
    

    Asp.NET / Javascript

    <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
    <script src="/Scripts/jquery.signalR.js" type="text/javascript"></script>
    <script src="http://localhost:8081/signalr"></script>
    
    <script type="text/javascript">
        $(function () {
           // create signalr hub connection
           myHub= $.connection.myHub;
    
           // start hub connection and call the send method
           $.connection.hub.start(function () {
               myHub.Send('Hello');
           });
        });
    </script>
    

    如果您有其他答案,请发表评论

    【讨论】:

      【解决方案2】:

      为了使它适用于 C# 和 ASP.NET,我必须使用“跨域”。

      在我使用的 JavaScript 中:

      <script type="text/javascript" src='http://localhost:8081/signalr/hubs'></script>
      

      并添加:

      $.connection.hub.url = 'http://localhost:8081/signalr'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多