WebSocket 立即关闭。

3
当我在React Native中打开WebSocket时,它会立即关闭,没有任何代码或原因。它还收到一个没有消息的错误。我通过ngrok http隧道使用WebSockets。我的服务器接收请求并完成连接。如果我立即发送数据,它将被接收,但大约1/4秒后,连接将关闭,我无法发送任何数据。然后我在服务器端收到一个错误,说连接在未完成握手的情况下关闭了。我做错了什么?这是在Android上的问题。
C#服务器代码:
            app.Use(async (context, next) => {
                if (!context.Request.Path.ToString().Contains("/notifications/")) {
                    await next();
                    return;
                }
                if (context.WebSockets.IsWebSocketRequest) {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
                } else {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                }
            });

JS客户端代码:

import Defaults from "../Defaults";
import Services from "../Services";

export default class NotificationService {
    constructor(){
        this.socket = null;
    }

    subscribe(userId, onmessage){
        let url = Defaults.webRoot.replace('http', 'ws') + '/notifications/' + userId;
        this.socket = new WebSocket(url);
        this.socket.onmessage = onmessage;
        this.socket.onerror = this.onerror;
        this.socket.onclose = this.onclose;
        this.socket.onopen = this.onopen;
    }

    onerror(event){
        alert('ws error: ' + event.message);
    }

    onclose(event){
        alert('ws closed: ' + event.code + ' - ' + event.reason);
    }

    onopen(event){
        alert('ws opened');
    }
}

onclose 显示 'ws closed: undefined - undefined' 时。

我在稍后的请求中使用了该套接字,但是我必须假设一旦请求完成,套接字并不会立即关闭,那样是愚蠢的。

当我的代码发送消息时,状态为 Open。然而,很明显它已经关闭,并且客户端无法接收消息。

1个回答

0
我想通了。如果我完成请求,由于某种原因,这也会关闭网络套接字。可能是响应中返回的某些内容使网络套接字混淆了,虽然我认为请求和套接字本身应该是完全不同的两个事物。
基本上,我必须添加这行代码才能保持套接字处于活动状态:while (!webSocket.State.HasFlag(WebSocketState.Closed) && !webSocket.State.HasFlag(WebSocketState.Aborted)) {} 我真的不确定那会对性能产生什么影响,并且我很担心我不得不这样做。我想你可以在while循环中使用Thread.Sleep调用,稍微减轻一下这个问题。
希望有人更好地理解这个问题,并知道如何更好地解决它。

不好意思,我在几年前就完全删除了这个项目。我猜测是在创建 Web Socket 后的 IsWebSocketRequest 块中。 - KthProg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接