95 lines
No EOL
3.6 KiB
C#
95 lines
No EOL
3.6 KiB
C#
using System.Collections.Concurrent;
|
|
|
|
namespace LarpixVoice;
|
|
|
|
public class Program
|
|
{
|
|
public static ConcurrentDictionary<string, ConcurrentDictionary<ulong, Session>> Rooms = new ();
|
|
|
|
public static ulong TotalBytesSent = 0;
|
|
public static ulong TotalBytesReceived = 0;
|
|
private static ulong CurrentBandwidthKps = 0;
|
|
|
|
public static void Main(string[] args)
|
|
{
|
|
Utils.LoadEnv();
|
|
|
|
Task.Run(async () =>
|
|
{
|
|
while (true)
|
|
{
|
|
await Task.Delay(1000);
|
|
|
|
ulong sentDelta = Interlocked.Read(ref TotalBytesSent);
|
|
ulong receivedDelta = Interlocked.Read(ref TotalBytesReceived);
|
|
Interlocked.Exchange(ref TotalBytesReceived, 0);
|
|
Interlocked.Exchange(ref TotalBytesSent, 0);
|
|
CurrentBandwidthKps = (sentDelta + receivedDelta);
|
|
}
|
|
});
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
builder.Logging.ClearProviders();
|
|
|
|
builder.WebHost.ConfigureKestrel(serverOptions =>
|
|
{
|
|
serverOptions.AddServerHeader = false;
|
|
serverOptions.ListenAnyIP(Utils.PORT);
|
|
});
|
|
|
|
var app = builder.Build();
|
|
|
|
app.UseWebSockets();
|
|
|
|
app.Use(async (HttpContext context, Func<Task> next) =>
|
|
{
|
|
try
|
|
{
|
|
context.Response.StatusCode = 200;
|
|
var path = context.Request.Path.Value;
|
|
var url = $"{context.Request.Scheme}://{context.Request.Host}";
|
|
if (path == "" || path?.Length > 512)
|
|
{
|
|
context.Response.Redirect(url + "/");
|
|
return;
|
|
}
|
|
|
|
context.Response.Headers["Access-Control-Allow-Origin"] = "*";//(context.Request.Headers["Origin"]).ToString().Replace("http://", "https://");
|
|
context.Response.Headers["Access-Control-Allow-Methods"]= "GET, POST, PUT, DELETE, OPTIONS";
|
|
context.Response.Headers["Access-Control-Allow-Headers"]= "Content-Type, Authorization";
|
|
context.Response.Headers["Access-Control-Allow-Credentials"]= "true";
|
|
switch (path)
|
|
{
|
|
case "/ws":
|
|
await Requests.Websocket(context);
|
|
return;
|
|
case "/load":
|
|
await context.Response.WriteAsync(Interlocked.Read(ref CurrentBandwidthKps).ToString());
|
|
return;
|
|
case "/room/users":
|
|
string roomId = context.Request.Query["room"].ToString();
|
|
context.Response.ContentType = "application/json";
|
|
|
|
if (Rooms.TryGetValue(roomId, out var room))
|
|
{
|
|
string[] users = room.Keys.Select(k => k.ToString()).ToArray();
|
|
await context.Response.WriteAsJsonAsync(users, JsonAppSerializerContext.Default.StringArray);
|
|
}
|
|
else
|
|
{
|
|
await context.Response.WriteAsJsonAsync(Array.Empty<string>(), JsonAppSerializerContext.Default.StringArray);
|
|
}
|
|
return;
|
|
default:
|
|
await next();
|
|
return;
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
}
|
|
});
|
|
Console.WriteLine("Starting server at port: " + Utils.PORT);
|
|
app.Run();
|
|
}
|
|
} |