private void BeginAccepting() { Start(); BeginAcceptTcpClient(ar => { try { TcpSocket socket = new TcpSocket((( TcpListener )ar.AsyncState).EndAcceptTcpClient(ar)); ClientConnectionRequested?.Invoke(socket); } catch (ObjectDisposedException) { /* Is caused when exitting the server while still listening for new clients */ } BeginAccepting(); }, this); }
private void Receive() { Active = true; Task.Run(() => { while (Active) { EndPoint newClient = new IPEndPoint(IPAddress.Any, 0); byte[] bytes = new byte[4096]; int length = _listener.ReceiveFrom(bytes, ref newClient); Packet p = new Packet(bytes.ToList().GetRange(0, length)); UdpSocket user = new UdpSocket(newClient); if (Clients.Where(c => c.RemoteEndPoint.ToString() == newClient.ToString()).ToList().Count == 0) { Clients.Add(user); ClientConnectionRequested?.Invoke(user); } ReceivedPacket?.Invoke(user, p); } }); }