/// <summary> /// Listen for new connections /// </summary> protected void Listen() { if (Logging) { Logger.Write("REGION", "Method [Listen]"); } Socket.Listen(Backlog); if (Logging) { Logger.Write("INFO", "Start listening for clients"); } while (Running) { Socket socket = Socket.Accept(); if (Logging) { Logger.Write("INFO", "New socket connected"); } TCPServerClient client = new TCPServerClient( socket, RandomGen.GenRandomUID(ClientsDict, UIDLength)); client.Joined = DateTime.Now; Thread clientThread = new Thread(() => ListenClient(client)); client.Thread = clientThread; clientThread.Start(); if (Logging) { Logger.Write("INFO", "Created client and started thread"); } } }
private async void Listen() { Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); Socket.Bind(new IPEndPoint(Address, Port)); Socket.Listen(Backlog); Logger.DebugWrite("INFO", $"WebSocket Server is now listening to new connections."); while (Running && !ListenToken.IsCancellationRequested) { Socket socket = null; try { socket = await Socket.AcceptAsync(); } catch (Exception) { continue; } WebSocketUser user = new WebSocketUser() { Socket = socket, Stream = await GetStream(socket), UID = RandomGen.GenRandomUID(Users, 128), Server = this }; if (user.Stream == null) { try { user.Socket.Shutdown(SocketShutdown.Both); } catch (Exception) { } continue; } while (!Users.TryAdd(user.UID, user)) { user.UID = RandomGen.GenRandomUID(Users, 12); } user.Writer = new WebSocketWriter(user); Logger.DebugWrite("INFO", $"New Socket connected to the WebSocket Server. {(user.Socket.RemoteEndPoint as IPEndPoint).Address}, UID: {user.UID}"); OnConnect?.Invoke(this, new ConnectEventArgs(user)); CancellationTokenSource cancel = new CancellationTokenSource(); Task task = new Task(async() => { try { await ListenClient(user); } catch (Exception er) { Logger.DebugWrite("FAILED", "Listen Error: ", er); RemoveClient(user, WebSocketDisconnection.Disconnect); } }, cancel.Token, TaskCreationOptions.LongRunning); task.Start(); user.ListenTask = task; user.ListenToken = cancel; } }