【问题标题】:SignalR for non-web application用于非 Web 应用程序的 SignalR
【发布时间】:2014-11-11 22:53:09
【问题描述】:

我有一个托管我的网站的网络服务器。我有一个单独的服务器正在运行某个任务。一旦有结果,我想 ping 当前登录到我的网络服务器上的客户端。这应该使用 SignalR 完成

这种没有运行服务器的服务的设置正在工作:

我有一个单独的项目来托管我的集线器:

public class NotificationHub : Hub
    {
        public string Activate() { return ""; }

        public override Task OnConnected()
        {
            string username = Context.User.Identity.Name.ToLower();
            Groups.Add(Context.ConnectionId, username);

            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            return base.OnDisconnected(stopCalled);
        }

        public override Task OnReconnected()
        {
            return base.OnReconnected();
        }
}

和客户端(此代码在登录时执行)

        var notificationHub = $.connection.notificationHub;

        notificationHub.client.connected = function () { console.log('client connected fired!'); };

        $.connection.hub.start().done(function () {
            notificationHub.server.activate();
        })

        notificationHub.client.testPing = function (message) {

            console.log("Message received: "+message);
        };

然后我有一个控件,它调用带有动作的 BubbleController

public ActionResult NotifyPing(string username, string message)
        {
                 SignalRfunctions.TestPing(username,message);

                 return Content("OK");
        }

其中 SignalRFunction 是一个包含所有通信功能的静态类,它包含在一个名为 Notifications 的单独项目中

public class SignalRfunctions
    {
        public static void TestPing(string username, string message)
         {
           IHubContext signalR = GlobalHost.ConnectionManager.GetHubContext<NotificationHub.NotificationHub>();

         signalR.Clients.Group(username).TestPing(message);
         }
    }

现在,当我编译所有内容时,以 Bob 身份登录并在浏览器控制台中执行此命令

$.get('/bubble/notifyping?username=bob&message=hi',function(){});

我在控制台中得到响应:

收到的消息:嗨

这是预期的(查看客户端 signalR 支持)

现在什么不起作用:

当我打电话时

SignalRfunctions.TestPing("bob"," hello from jobrunner");

来自在我的服务中(非网络相关项目),即使我以 bob 身份登录,我也没有在浏览器控制台中得到任何响应。基本上,SignalR 在我的网络应用程序中为我工作,当我尝试与我的服务器运行服务桥接时,我没有连接。

我做错了什么?

(我确实在调试下运行了所有内容以检查是否有任何明显的错误,但没有发现)


更新:在最初的问题中,我错过了一段初始化 SignalR 的代码:

[assembly: OwinStartup(typeof(WebApp.OwinStartup))]
namespace WebApp
{
    public class OwinStartup
    {
        public void Configuration(IAppBuilder app)
        {
            UsernameProvider usernameProvider = new UsernameProvider();

            GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => usernameProvider);

            app.MapSignalR();
        }
    }
}

UsernameProvider 类在这里:

public class UsernameProvider : IUserIdProvider
{
    public string GetUserId(IRequest request)
    {
        string username = request.User.Identity.Name.ToLower();

        return username;

    }
}

【问题讨论】:

    标签: .net asp.net-mvc signalr signalr-hub


    【解决方案1】:

    除了启动例程之外,您已经显示了大部分服务器逻辑。 它是您连接客户收听路径的地方。 我也看不到您在告诉客户端在连接到服务器时应该在哪里查看,但是由于它要回到服务器,所以我猜您已成功将其指向那里。

    http://www.asp.net/aspnet/overview/owin-and-katana/owin-startup-class-detection

    甚至在这里http://www.asp.net/signalr/overview/deployment/tutorial-signalr-self-host

    [assembly: OwinStartup(typeof(Startup))]
    namespace YourSignalR
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.UseCors(CorsOptions.AllowAll);
    
                // Debugging only
                var hubConfiguration = new HubConfiguration();
                hubConfiguration.EnableDetailedErrors = true;
    
                // custom path for clients to listen to. By default it is /signalr
                app.MapSignalR(Resources.Url, hubConfiguration);
            }
        }
    }
    

    更新 - 我真的很忙。

    从你所说的你有一个 Web 服务器作为 SignalR 服务器和一个与之通信的 Web 客户端。您希望拥有一个单独的基于 SOA 的解决方案,该解决方案上具有服务或调用其他服务。您希望服务解决方案能够访问 SignalR Web 服务器。

    根据您的说法,我不相信您从服务解决方案联系的 HubContext 与 Web 客户端已连接到的上下文相同,因此何时无法联系你告诉它发送消息。我相信你可以调试和检查两者的身份。

    我熟悉的两种方法可以帮助您。

    1. 如果您愿意,您可以创建一个自托管的 SingalR 服务器,您可以使用您的服务后端来实现它。我用它来让 WPF 客户端接收来自对内部服务和外部 Web 服务进行的服务调用的更新。

    2. 另一种方法是您可以将您的服务项目视为另一个客户端,并让它通过 SignalR 连接到 Web 服务器以与其他客户端/组进行通信。这样,它们都是同步的并且处于相同的上下文中。因此,服务器想要发送的任何内容都只会调用来自 Web 服务器的方法来告诉其他客户端/组。

    如果我想到别的东西,我会发布它。

    如果您想使用这种方法,我做了一个简单的示例,我使用 Clients.All 而不是设置组以使其更简单并显示它有效。

    网页部分 集线器

    namespace SignalRChatter
    {
        /// <summary>
        /// install-package Microsoft.AspNet.SignalR
        /// </summary>
        public class ChatHub : Hub
        {
            public void Send(string name, string message)
            {
                Clients.All.broadcastMessage(name, message);
            }
        }
    }
    

    启动

    [assembly: OwinStartup(typeof(SignalRChatter.Startup))]    
    namespace SignalRChatter
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // For more information on how to configure your application, 
                // visit http://go.microsoft.com/fwlink/?LinkID=316888
                app.MapSignalR();
            }
        }
    }
    

    HTML 正文

    <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. you are using -->
        <script src="Scripts/jquery-2.1.1.min.js"></script>
        <!--Reference the SignalR library. you are using-->
        <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
        <!--Reference the autogenerated SignalR hub script. you are using -->
        <script src="signalr/hubs"></script>
        <!--Add script to update the page and send messages.-->
        <script type="text/javascript">
            $(function () {
                // Declare a proxy to reference the hub.
                var chat = $.connection.chatHub;
                // Create a function that the hub can call to broadcast messages.
                chat.client.broadcastMessage = 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>
    

    服务器端表现得像客户端 您在控制台中输入的任何内容都将发送到 Web 客户端。 您可能会调用一个专门用于后端客户端的方法来与 Web 客户端对话。由你决定。

    确保安装此软件包: 此软件包支持 .NET 4 和 .NET 4.5 的 WinRT、Silverlight、WPF、控制台应用程序和 Windows Phone 客户端。 PM> 安装包 Microsoft.AspNet.SignalR.Client

    namespace SomeConsoleApp
    {
        class Program
        {
    
            //PM> Install-Package Microsoft.AspNet.SignalR.Client 
            static void Main(string[] args)
            {
                var hubConnection = new HubConnection("http://localhost:YOURPORT/");
                IHubProxy chatHubProxy = hubConnection.CreateHubProxy("ChatHub");
    
                // it doesn't need to listen to the other clients but was testing to make sure it can. all it needs to do is send to the others.
                chatHubProxy.On<string, string>("broadcastMessage", (name, message) => Console.WriteLine("update for {0} new message {1}", name, message));
                Connect(hubConnection);
    
                var input = "Server Acting Like A Client";
                Console.WriteLine(input);
                while (!input.Equals("Exit", StringComparison.InvariantCultureIgnoreCase))
                {
                    input = Console.ReadLine();
                    Invoker(chatHubProxy, input);
                }
    
                Console.ReadLine();
            }
    
            static async void Connect(HubConnection hubConnection)
            {
                try
                {
                    Console.WriteLine("starting");
                    await hubConnection.Start();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
    
            static async void Invoker(IHubProxy chatHubProxy, string input)
            {
                await chatHubProxy.Invoke("Send", "Server Client", input);
            }
        }
    }
    

    【讨论】:

    • 你说得对,我没有发布一些代码,但我想,因为我可以从我的网络上得到一切工作。应用程序。我唯一的问题是我无法从我的非 Web 服务器 ping Web 客户端。我用 SignarR init 的额外代码修改了我的问题。我想知道我是否应该在我的非网络相关应用程序中进行某种初始化?
    【解决方案2】:

    如果我理解得很好,您有 1 个网络应用程序和另一个应用程序。

    您希望当第二个应用发生问题时,通过 signalR 向登录到您网站的人发送消息。

    如果是这种情况,您可以使用 httpclient 从应用程序调用您的 web 应用程序

    http://www.dotnetperls.com/httpclient

    到您的端点 /bubble/notifyping 传递您想要的消息。

    【讨论】:

    • 感谢您的想法。我现在就调查一下。虽然,我认为,当我打电话给我的集线器时它应该是自动的,但你建议的是一个很好的解决方案 - 可能工作得很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    相关资源
    最近更新 更多