SimpleVoiceMeetingServerModule.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.Collections.Concurrent;
  2. using System.Net;
  3. using System.Net.WebSockets;
  4. using System.Text;
  5. namespace SimpleWebChat.ConHost;
  6. public static class SimpleVoiceMeetingServerModule
  7. {
  8. private static readonly ConcurrentDictionary<int, WebSocket> OnlineSessions = new();
  9. public static void ProcessRequest(HttpListenerContext context, int currentSessionId)
  10. {
  11. WebSocket sck = null;
  12. try
  13. {
  14. sck = context.AcceptWebSocketAsync("svmp").Result.WebSocket;
  15. OnlineSessions[currentSessionId] = sck;
  16. Console.WriteLine($"Request #{currentSessionId:00000} VoiceMeet WebSocket Session Start");
  17. sck.BroadCastFaf($"Session#{currentSessionId:X4} Connected, Online sessions:{OnlineSessions.Count}");
  18. var buffer = new byte[16384];
  19. while (true)
  20. {
  21. var r = sck.ReceiveAsync(buffer, default).Result;
  22. if (r.Count == 0) break;
  23. sck.BroadCastFaf(new ArraySegment<byte>(buffer, 0, r.Count));
  24. }
  25. }
  26. catch (Exception)
  27. {
  28. try
  29. {
  30. if (sck != null && sck.State != WebSocketState.Aborted)
  31. {
  32. sck.CloseAsync(WebSocketCloseStatus.InternalServerError, "Error", default).Wait();
  33. }
  34. }
  35. catch (Exception e)
  36. {
  37. Console.WriteLine(e);
  38. }
  39. }
  40. OnlineSessions.TryRemove(currentSessionId, out _);
  41. sck.BroadCastFaf($"Session#{currentSessionId:X4} Disconnected, Online sessions:{OnlineSessions.Count}");
  42. }
  43. private static void BroadCastFaf(this WebSocket sck, string text)
  44. {
  45. var all = OnlineSessions.Values.ToArray();
  46. foreach (var s in all)
  47. {
  48. try
  49. {
  50. s.SendAsync(text);
  51. }
  52. catch
  53. {
  54. //FUCK ERR
  55. }
  56. }
  57. }
  58. private static void BroadCastFaf(this WebSocket sck, ArraySegment<byte> binary)
  59. {
  60. var all = OnlineSessions.Values.ToArray();
  61. foreach (var s in all)
  62. {
  63. if (s == sck) continue;
  64. try
  65. {
  66. s.SendAsync(binary);
  67. }
  68. catch
  69. {
  70. //FUCK ERR
  71. }
  72. }
  73. }
  74. private static Task SendAsync(this WebSocket sck, string text) => sck.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, default);
  75. private static void SendSync(this WebSocket sck, string text) => SendAsync(sck, text).Wait();
  76. private static Task SendAsync(this WebSocket sck, ArraySegment<byte> bin) => sck.SendAsync(bin, WebSocketMessageType.Binary, true, default);
  77. private static void SendSync(this WebSocket sck, ArraySegment<byte> bin) => SendAsync(sck, bin).Wait();
  78. }