当我在React Native中打开WebSocket时,它会立即关闭,没有任何代码或原因。它还收到一个没有消息的错误。我通过ngrok http隧道使用WebSockets。我的服务器接收请求并完成连接。如果我立即发送数据,它将被接收,但大约1/4秒后,连接将关闭,我无法发送任何数据。然后我在服务器端收到一个错误,说连接在未完成握手的情况下关闭了。我做错了什么?这是在Android上的问题。
C#服务器代码:
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
。然而,很明显它已经关闭,并且客户端无法接收消息。
IsWebSocketRequest
块中。 - KthProg