关于 mongodb:SignalR Core – 错误:Websocket 关闭,状态码:1006

SignalR Core - Error: Websocket closed with status code: 1006

我在 Angular 应用程序中使用 SignalR。当我在 Angular 中销毁组件时,我还想停止与集线器的连接。我使用命令:

1
this.hubConnection.stop();

但我在 Chrome 控制台中收到错误消息:
Websocket 以状态码关闭:1006

在边缘:错误错误:未捕获(在Promise中):错误:由于连接关闭而取消调用。错误:由于连接关闭而取消调用。

它确实有效并且连接已停止,但我想知道为什么会出现错误。

这就是我启动集线器的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
this.hubConnection = new HubConnectionBuilder()
      .withUrl("/matchHub")
      .build();

    this.hubConnection.on("MatchUpdate", (match: Match) => {
      // some magic
    })

    this.hubConnection
      .start()
      .then(() => {
        this.hubConnection.invoke("SendUpdates");
      });

编辑

我终于找到了问题所在。它是由来自 Mongo 的更改流引起的。如果我从 SendUpdates() 方法中删除代码,则会触发 OnDisconnected。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    public class MatchHub : Hub
    {
    private readonly IMatchManager matchManager;

    public MatchHub(IMatchManager matchManager)
    {
        this.matchManager = matchManager;
    }

    public async Task SendUpdates() {
        using (var changeStream = matchManager.GetChangeStream()) {
            while (changeStream.MoveNext()) {
                var changeStreamDocument = changeStream.Current.FullDocument;
                if (changeStreamDocument == null) {
                    changeStreamDocument = BsonSerializer.Deserialize<Match>(changeStream.Current.DocumentKey);
                }
                await Clients.Caller.SendAsync("MatchUpdate", changeStreamDocument);
            }
        }
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        await base.OnDisconnectedAsync(exception);
    }
}

来自管理器的方法 GetChangeStream。

1
2
3
        ChangeStreamOptions options = new ChangeStreamOptions() { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
        var watch =  mongoDb.Matches.Watch(options).ToEnumerable().GetEnumerator();
        return watch;

但我不知道如何解决它。


这可能有很多原因,但我认为很可能是这个:

I think this is because of how the server is handling the connected / disconnected events. I can't say for sure but the connection closing needs to handled correctly on the server also with code. Try overriding the built in On Connected /Disconnected methods on the server and see. My assumption only is that you're closing it but the server isn't closing properly and therefore not relaying the proper closed response.

作为评论发现:get the reason why websockets closed with close code 1006

您不需要更改连接/断开连接,因为 evrything 工作正常。但作为答案,这是最有可能的。


它会抛出错误,因为回调没有正确清除。

而且是websocket返回数据造成的。

通常它应该像

一样返回

enter

事实证明,我可以利用调用响应来通知客户端停止集线器。所以它不会触发赛车问题。