/// <summary> /// Listens for incoming connection requests. Run this method on a seperate thread. /// </summary> private void Listen() { TcpListener listener = null; try { listener = new TcpListener(IPAddress.Any, this.ListeningPort); listener.Start(); while (this.IsRunning) { if (!listener.Pending()) { Thread.Sleep(50); continue; } TcpClient tc = listener.AcceptTcpClient(); CombobotClientDescriptor descriptor = new CombobotClientDescriptor(tc, string.Empty); this.ConnectedClients.Add(descriptor); if (this.ClientConnected != null) { this.ClientConnected(descriptor); } Thread t = new Thread(new ParameterizedThreadStart(this.HandleClient)); t.Start(descriptor); } } catch { } finally { if (listener != null) { listener.Stop(); } } }
/// <summary> /// Handles a connected client. Run this method on a seperate thread. /// </summary> /// <param name="combobotClientDescriptor">A CombobotClientDescriptor object.</param> private void HandleClient(object combobotClientDescriptor) { CombobotClientDescriptor descriptor = (CombobotClientDescriptor)combobotClientDescriptor; try { TcpClient tc = descriptor.TcpClient; NetworkStream nstream = tc.GetStream(); while (this.IsRunning) { Objects.Packet p = Objects.Packet.GetNextPacket(nstream); if (p.Length == 0) { break; // disconnected } p.GetUInt16(); // length, not needed switch ((PacketType)p.GetByte()) { case PacketType.Ping: descriptor.SetRTT((ushort)descriptor.GetElapsedMilliseconds()); if (this.ClientPingReceived != null) { this.ClientPingReceived(descriptor); } break; case PacketType.PlayerInfo: descriptor.CharacterName = p.GetString(); break; } } } catch { } finally { if (descriptor.TcpClient != null) { descriptor.TcpClient.Close(); } this.ConnectedClients.Remove(descriptor); if (this.ClientDisconnected != null) { this.ClientDisconnected(descriptor); } } }