// Listens to incoming client connections and spawns a new client "Zombie" object // when a pending connection is detected. public void Listen() { try { listener.Start(); while (isListening) { if (listener.Pending()) { TcpClient client = listener.AcceptTcpClient(); Log("Accepted Client Connection"); Zombie zombie = new Zombie(mainForm, client); zombies.Add(zombie); Thread zombieThread = new Thread(new ThreadStart(zombie.ListenForData)); zombieThread.IsBackground = true; zombieThread.Start(); mainForm.UpdateStatus(); } // Need to test this sleep, see if it messes up communication. // Using this due to high CPU usage on server. Thread.Sleep(100); } }catch (Exception ex) { Log("Listener error: " + ex.ToString()); } }
// Listen on the network stream for data coming from the client. public void ListenForData() { try { while (IsAlive() && IsActive()) { if (sslSecured ? sslStream.CanRead : netStream.CanRead) { try { byte[] bytes = new byte[1024]; string data = null; int i; if ((i = sslSecured ? sslStream.Read(bytes, 0, bytes.Length) : netStream.Read(bytes, 0, bytes.Length)) != 0) { // convert recieved bytes to string data data = Encoding.ASCII.GetString(bytes, 0, i); curData += data; // Log data if not binary if (!data.Contains("[[BINARY]]") && !bufferBytes) { Log("Data recieved: " + data); } // If we are receiving binary data, place data into buffer. // To support things such as multiple monitors being viewed at once, we need to have some sort // of buffer collection. if (data.Contains("[[BINARY]]")) { bufferBytes = true; } if (bufferBytes) { try { bytes.CopyTo(dataBuffer, bufferPos); bufferPos += i; } catch { } } // Handles the first command. if (FirstCommandIsClosed(curData)) { HandleData(FirstCommand()); } } } catch (Exception ex) { Log("Error reading data: " + ex.ToString()); } Application.DoEvents(); } // Need to test this sleep, see if it messes up communication. // Using this due to high CPU usage on server. Thread.Sleep(1); } } catch (Exception ex) { Log("Stream lost connection: " + ex.ToString()); } finally { Log("Lost connection to: " + IP); active = false; // remove entry from listview if connection is lost/closed RemoveFromListView(); mainForm.UpdateStatus(); } }