WebSocket立即关闭

时间:2018-06-14 00:48:09

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

当我在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 :(得分:0)

我明白了。如果我完成请求,由于某种原因,这也会关闭Web套接字。虽然我假设了请求并且套接字本身将是两个完全不同的东西,但响应中必须有一些东西会让Web套接字混乱。

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

我真的不确定这会对演出产生什么影响,我担心我必须这样做。我想你可以通过while循环中的Thread.Sleep调用来降低它的可怕性。

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