Skip to content

Commit

Permalink
✨ [next C#] 现在可以支持WebSocket连接了
Browse files Browse the repository at this point in the history
  • Loading branch information
kingsword09 committed Jul 3, 2023
1 parent b389d0c commit 2f9439f
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions next/dweb-browser/MicroService/src/Sys/Http/Net/NetServer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace DwebBrowser.MicroService.Sys.Http.Net;
using System.Net.WebSockets;

namespace DwebBrowser.MicroService.Sys.Http.Net;

public interface IProtocol
{
Expand Down Expand Up @@ -55,6 +57,7 @@ public record ListenOptions(int Port, string Hostname = "localhost");

public static class NetServer
{
static Debugger Console = new("NetServer");
/// <summary>
/// TODO 这里应该提供Stop函数来终止服务
/// </summary>
Expand All @@ -80,9 +83,16 @@ public static IServerInfo<HttpListener> HttpCreateServer(ListenOptions listenOpt
{
var context = listener.GetContext();

Task.Factory.StartNew(() =>
Task.Factory.StartNew(async () =>
{
HandlerAsync(context, handler).Wait();
if (context.Request.IsWebSocketRequest)
{
WebSocketHandlerAsync(context).Wait();
}
else
{
HttpHandlerAsync(context, handler).Wait();
}
}, TaskCreationOptions.LongRunning);
}
}, TaskCreationOptions.LongRunning);
Expand All @@ -96,7 +106,21 @@ public static IServerInfo<HttpListener> HttpCreateServer(ListenOptions listenOpt
new HttpProtocol("http://", "http:", 80));
}

private static async Task HandlerAsync(HttpListenerContext context, HttpHandler handler)
private static async Task WebSocketHandlerAsync(HttpListenerContext context)
{
var webSocket = await context.AcceptWebSocketAsync(null)!;
var chunk = new byte[1000];
/// Echo
while (webSocket.WebSocket.State == WebSocketState.Open)
{
var result = await webSocket.WebSocket.ReceiveAsync(new ArraySegment<byte>(chunk), CancellationToken.None)!;
var bytes = chunk[0..result.Count];
await webSocket.WebSocket.SendAsync(new ArraySegment<byte>(bytes), result.MessageType, result.EndOfMessage, CancellationToken.None);
}
Console.Log("WebSocket Server", "End");
}

private static async Task HttpHandlerAsync(HttpListenerContext context, HttpHandler handler)
{
var request = context.Request;
using var response = context.Response;
Expand All @@ -112,6 +136,5 @@ private static async Task HandlerAsync(HttpListenerContext context, HttpHandler
response.StatusCode = 502;
}
}

}

0 comments on commit 2f9439f

Please sign in to comment.