localhost上的SignalR

时间:2017-03-15 13:05:36

标签: c# asp.net localhost signalr signalr-2

我正在运行一个带有localhost http://*:52080的服务器。 在同一台计算机上,我运行客户端并尝试连接到本地IP中心http://192.168.1.102:52080/signalr。一切都运作良好。

但是,如果我在另一台计算机上运行客户端(来自同一本地网络)并尝试连接到http://192.168.1.102:52080/signalr,则它无法连接。客户端捕获异常("System.AggregateException" in mscorlib.dll)。

集线器计算机上的端口52080已打开。

失败的原因是什么?

服务器:

using System;
using Microsoft.Owin.Hosting;

public class Program
{
    static void Main(string[] args)
    {
        string url = "http://*:52080";
        using (WebApp.Start<Startup>(url))
        {
            Console.WriteLine("Server running at {0}\n", url);
            Console.ReadLine();
        }
    }
}

Startup.cs

using Owin;
using Microsoft.Owin.Cors;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}

SGHub.cs

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using System.Collections.Generic;

public class SGHub : Hub
{   
    public static List<string> Users = new List<string>();

    public override Task OnConnected()
    {
        Console.WriteLine("\nOnConnected {0}", Context.ConnectionId);
        Users.Add(Context.ConnectionId);

        Clients.Caller.broadcastMessage("Server:", "Successful connection");
        Clients.Others.broadcastMessage("Server:", "New connection");

        return (base.OnConnected());
    }
}

客户端:

using System; 
using Microsoft.AspNet.SignalR.Client; 
using Microsoft.AspNet.SignalR.Client.Hubs; 
using Newtonsoft.Json.Linq; 

class Program
{
    static void Main(string[] args)
    {
        string serverURL = "http://192.168.1.102:52080/signalr";

        Console.WriteLine("Connection to {0}\n", serverURL);
        HubConnection hubConnection = new HubConnection(serverURL);
        IHubProxy myHubProxy = hubConnection.CreateHubProxy("StartGameHub");

        myHubProxy.On<string, string>("Send", (name, message) => Console.Write("Recieved addMessage: " + name + ": " + message + "\n"));
        myHubProxy.On("heartbeat", () => Console.Write("Recieved heartbeat \n"));

        Subscription subscription = myHubProxy.Subscribe("broadcastMessage");
        subscription.Received += SubscriptionData;

        while (true)
        {
            string key = Console.ReadLine();

            if (key.ToUpper() == "A")
            {
                try
                {
                    Console.WriteLine("Start connect..");
                    hubConnection.Start().Wait();
                }
                catch (System.AggregateException e)
                {
                    Console.WriteLine("Connected fauld :(");
                }
            }
        }
    }

    private static void SubscriptionData(IList<JToken> obj)
    {
        Console.WriteLine(obj[1].ToString());
    }
}

1 个答案:

答案 0 :(得分:0)

问题不在代码和实现方法中,但在路由器的平庸故障中,重新启动并重新启动所有计算机(以防万一)后一切正常。