【发布时间】: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