Qui*_*nch 5 .net javascript c# websocket .net-core
您好,我目前正在为我的非常基本的站点实现一个 websocket 组件。我正在运行 .NET Core 3.1 HTTP 侦听器来提供 html 服务,我一直被实现 websockets 难住了。
我以前在 C# 中使用过 TCP,并且了解所有内容的流程,但 websockets 对我来说是新事物。这是接受 websockets 的 C# 代码
[Route("/socket", "GET")]
public static async Task upgrade(HttpListenerContext c)
{
if (!c.Request.IsWebSocketRequest)
{
c.Response.StatusCode = 400;
c.Response.Close();
return;
}
try
{
var sock = (await c.AcceptWebSocketAsync(null)).WebSocket;
byte[] buff = new byte[1024];
var r = await sock.ReceiveAsync(buff, System.Threading.CancellationToken.None);
}
catch (Exception x)
{
Console.WriteLine($"Got exception: {x}");
}
//WebSocketHandler.AddSocket(sock);
}
Run Code Online (Sandbox Code Playgroud)
我添加var r = await sock.ReceiveAsync(buff, System.Threading.CancellationToken.None);到这个函数是因为最初我在我的 WebSocketHandler 类中遇到了异常,所以我将代码移到一个函数中进行测试。
这是客户端:
<script>
let socket = new WebSocket("ws://localhost:3000/socket");
socket.onopen = function (event) {
console.log("[ OPENED ] - Opened Websocket!");
};
socket.onclose = function (event) {
console.log("[ CLOSED ] - Socket closed");
};
socket.onerror = function (error) {
console.log("[ ERROR ] - Got websocket error:");
console.error(error);
};
socket.onmessage = function (event) {
// This function will be responsible for handling events
console.log("[ MESSAGE ] - Message received: ");
const content = JSON.parse(event.data);
console.log(content);
};
</script>
Run Code Online (Sandbox Code Playgroud)
这是客户端控制台中的输出:
Navigated to http://127.0.0.1:5500/index.html
index.html:556 [ OPENED ] - Opened Websocket!
index.html:569 [ CLOSED ] - Socket closed
Run Code Online (Sandbox Code Playgroud)
这是来自 C# 服务器的异常:
Got exception: System.Net.WebSockets.WebSocketException (997): The remote party closed the WebSocket connection without completing the close handshake.
at System.Net.WebSockets.WebSocketBase.WebSocketOperation.Process(Nullable`1 buffer, CancellationToken cancellationToken)
at System.Net.WebSockets.WebSocketBase.ReceiveAsyncCore(ArraySegment`1 buffer, CancellationToken cancellationToken)
at SwissbotCore.HTTP.Routes.UpgradeWebsocket.upgrade(HttpListenerContext c) in C:\Users\plynch\source\repos\SwissbotCore\SwissbotCore\HTTP\Routes\UpgradeWebsocket.cs:line 29
Run Code Online (Sandbox Code Playgroud)
如果需要,我可以提供客户端发送的 http 请求,但我对此感到非常困惑,任何帮助将不胜感激。
您可能需要阅读RFC 6455 中 1.4 节中的“关闭握手”以及RFC 6455 中 7.1.1 节中的“关闭 WebSocket 连接”。
本质上,您需要在终止套接字之前让 WebSocket 端点知道您将关闭套接字。
对于您的服务器端,您可能应该捕获此异常,因为当网络问题发生时,这也可能发生在生产场景中。
| 归档时间: |
|
| 查看次数: |
2423 次 |
| 最近记录: |