Javascript WebSocket立即关闭
在React Native中打开WebSocket时,它会立即关闭。没有代码或理由。它还接收到一个没有消息的错误。我通过ngrok http隧道使用WebSocket。我的服务器收到请求并完成连接。如果我立即发送数据,它将被接收,但大约1/4秒后,连接关闭,我无法发送任何数据。然后,我在服务器端收到一个错误,说连接在没有完成握手的情况下关闭了。我做错了什么?这是安卓上的 C#服务器代码:Javascript WebSocket立即关闭,javascript,c#,react-native,websocket,kestrel-http-server,Javascript,C#,React Native,Websocket,Kestrel Http Server,在React Native中打开WebSocket时,它会立即关闭。没有代码或理由。它还接收到一个没有消息的错误。我通过ngrok http隧道使用WebSocket。我的服务器收到请求并完成连接。如果我立即发送数据,它将被接收,但大约1/4秒后,连接关闭,我无法发送任何数据。然后,我在服务器端收到一个错误,说连接在没有完成握手的情况下关闭了。我做错了什么?这是安卓上的 C#服务器代码: app.Use(async (context, next) => {
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”
我在以后的请求中使用了套接字,但我必须假设套接字不会在请求完成后立即关闭,这将是愚蠢的
当到达发送消息的“我的代码”时,状态为“打开”。但是它显然是关闭的,在客户端不接收消息。我发现了。如果我完成了请求,出于某种原因,这也会关闭web套接字。虽然我假设请求和套接字本身是两个完全不同的东西,但响应中一定有什么东西会混淆web套接字 基本上,我必须添加这一行来保持套接字的活动状态:
while(!webSocket.State.HasFlag(WebSocketState.Closed)&&!webSocket.State.HasFlag(WebSocketState.Aborted)){}
我真的不确定这会对性能产生什么影响,我担心我必须这样做。我想你可以在while循环中使用线程.Sleep
调用使它稍微不那么糟糕
希望有人能更好地理解这个问题,并且知道如何更好地解决这个问题。不,对不起,我在几年前就完全删除了整个项目。在创建web套接字之后,我将在
IsWebSocketRequest
块中进行假设。