123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- using System.Collections.Concurrent;
- using System.Net;
- using System.Net.WebSockets;
- using System.Text;
- namespace SimpleWebChat.ConHost;
- public static class SimpleVoiceMeetingServerModule
- {
- private static readonly ConcurrentDictionary<int, WebSocket> OnlineSessions = new();
- public static void ProcessRequest(HttpListenerContext context, int currentSessionId)
- {
- WebSocket sck = null;
- try
- {
- sck = context.AcceptWebSocketAsync("svmp").Result.WebSocket;
- OnlineSessions[currentSessionId] = sck;
- Console.WriteLine($"Request #{currentSessionId:00000} VoiceMeet WebSocket Session Start");
- sck.BroadCastFaf($"Session#{currentSessionId:X4} Connected, Online sessions:{OnlineSessions.Count}");
- var buffer = new byte[16384];
- while (true)
- {
- var r = sck.ReceiveAsync(buffer, default).Result;
- if (r.Count == 0) break;
- sck.BroadCastFaf(new ArraySegment<byte>(buffer, 0, r.Count));
- }
- }
- catch (Exception)
- {
- try
- {
- if (sck != null && sck.State != WebSocketState.Aborted)
- {
- sck.CloseAsync(WebSocketCloseStatus.InternalServerError, "Error", default).Wait();
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- }
- }
- OnlineSessions.TryRemove(currentSessionId, out _);
- sck.BroadCastFaf($"Session#{currentSessionId:X4} Disconnected, Online sessions:{OnlineSessions.Count}");
- }
- private static void BroadCastFaf(this WebSocket sck, string text)
- {
- var all = OnlineSessions.Values.ToArray();
- foreach (var s in all)
- {
- try
- {
- s.SendAsync(text);
- }
- catch
- {
- //FUCK ERR
- }
- }
- }
- private static void BroadCastFaf(this WebSocket sck, ArraySegment<byte> binary)
- {
- var all = OnlineSessions.Values.ToArray();
- foreach (var s in all)
- {
- if (s == sck) continue;
- try
- {
- s.SendAsync(binary);
- }
- catch
- {
- //FUCK ERR
- }
- }
- }
- private static Task SendAsync(this WebSocket sck, string text) => sck.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, default);
- private static void SendSync(this WebSocket sck, string text) => SendAsync(sck, text).Wait();
- private static Task SendAsync(this WebSocket sck, ArraySegment<byte> bin) => sck.SendAsync(bin, WebSocketMessageType.Binary, true, default);
- private static void SendSync(this WebSocket sck, ArraySegment<byte> bin) => SendAsync(sck, bin).Wait();
- }
|