.NET Core 2.1 / Angular - SignalR只需2分钟即可连接到集线器

时间:2018-06-01 08:19:27

标签: c# asp.net angular asp.net-core signalr

我有一个Ionic应用程序,我希望它连接到我的套接字。这在SignalR预览中工作得很好,而且它仍然可以,但由于某种原因连接需要2分钟......

enter image description here

连接时我也会遇到一些错误:

enter image description here

这是我的javascript代码:

ngOnInit() {

    const connection = new signalR.HubConnectionBuilder()
          .withUrl("http://192.168.178.11:8040/socket?sessionId=3dc1dc11")
          .build();

    connection.on("ReceiveMessage", message => {
      console.log(message);

      this.zone.run(() => {
        if(this.locked == true) {
          this.locked = false
        } else {
          this.locked = true;
        }
      });

      console.log(this.locked);
    });

    connection.start().catch(err => console.error);

}

这是我的中心:

public class DeviceHub : Hub
{
        public override Task OnConnectedAsync()
        {
            var sessionId = Context.GetHttpContext().Request.Query["sessionId"];

            return Groups.AddToGroupAsync(Context.ConnectionId, sessionId);
        }
}

这是我在Startup.cs中的配置:

app.UseSignalR(routes =>
{
    routes.MapHub<DeviceHub>("/socket");
});

现在我的问题是:我该如何解决这个问题?

编辑1:

延迟发生在调用OnConnectedAsync()方法之前。

编辑2:

我认为我应该添加的另一件事是它直接向我的API发出请求:

ws://192.168.178.11:8040/socket?sessionId=3dc1dc11&id=Pt-JDlSPq2_WEIl-8cdPZA

这就是需要两分钟才完成的请求。

编辑3:

我想指出的另一件事是我正在运行代理。我无法将手机中的directy连接到API,因此我使用了proxy。我不知道这是否与它有任何关系,但我只想指出它以防万一。

1 个答案:

答案 0 :(得分:4)

嗯...

对我感到羞耻。

代理导致了这个问题。

我在Visual Studio中为自己的IP添加了绑定,现在可以正常工作。

要执行此操作,请打开\APPLICATION_FOLDER\.vs\config\applicationhost.config

然后查找<bindings>并添加您自己的<bindings> <binding protocol="http" bindingInformation="*:63251:localhost" /> <binding protocol="https" bindingInformation="*:44333:localhost" /> <binding protocol="http" bindingInformation="*:63251:192.168.178.11" /> <binding protocol="https" bindingInformation="*:44333:192.168.178.11" /> </bindings>

示例:

if(new Date().getDay() % 6 === 0) {
    setInterval(function() {
        // your code
    }, 1000);
}

保存,然后就完成了。

注意:

从现在开始,您必须以管理员身份启动Visual Studio,否则您的应用程序将无法启动。