【问题标题】:WebSocket is closed immediatelyWebSocket 立即关闭
【发布时间】:2018-06-14 00:48:09
【问题描述】:

当我在 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。然而它显然是关闭的,并且在客户端不接收消息。

【问题讨论】:

    标签: javascript c# react-native websocket kestrel-http-server


    【解决方案1】:

    我想通了。如果我完成了请求,出于某种原因,这也会关闭 Web 套接字。尽管我认为请求和套接字本身将是两个完全不同的东西,但响应中一定有一些东西会混淆 Web 套接字。

    我基本上必须添加这一行以保持套接字处于活动状态:while (!webSocket.State.HasFlag(WebSocketState.Closed) && !webSocket.State.HasFlag(WebSocketState.Aborted)) {}

    我真的不确定这会对性能产生什么影响,我担心我必须这样做。我想你可以通过在 while 循环中调用 Thread.Sleep 来让它稍微不那么糟糕。

    希望有人能更好地理解这个问题,并且知道如何更好地解决这个问题。

    【讨论】:

    • 不,抱歉,几年前我完全删除了整个项目。我会假设在 Web 套接字创建后的 IsWebSocketRequest 块中。
    猜你喜欢
    • 2017-03-20
    • 2018-10-12
    • 2022-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多