public void StartListening() { SharedStateObj = new SharedState(); SharedStateObj.ContinueProcess = true; SharedStateObj.NumberOfClients = 0; SharedStateObj.Ev = new AutoResetEvent(false); TcpListener listener = new TcpListener(portNum); try { listener.Start(); int ClientNbr = 0; // Start listening for connections. Debug.WriteLine("Waiting for a connection..."); while (SharedStateObj.ContinueProcess) { TcpClient handler = listener.AcceptTcpClient(); SharedStateObj.NumberOfClients++; Debug.WriteLine("Client#{0} accepted!", ClientNbr); ConnectionHandler _connection = new ConnectionHandler(handler); _connection.Disconnected += new EventHandler(this.client_Disconnected); ThreadPool.QueueUserWorkItem(new WaitCallback(_connection.Process), SharedStateObj); this.Clients.Add(_connection); this.RaiseClientConnected(_connection); } listener.Stop(); } catch (Exception ex) { Debug.WriteLine("StealME.Exception:" + ex.ToString()); } // Stop and wait all Client connections to end SharedStateObj.ContinueProcess = false; SharedStateObj.Ev.WaitOne(); }
public void Process(Object o) { this._sharedState = (SharedState)o; // Incoming data from the Client. string data = null; // Data buffer for incoming data. byte[] bytes; byte[] messageBytes; this.LastPing = DateTime.Now; if (this.ClientSocket != null) { NetworkStream networkStream = this.ClientSocket.GetStream(); this.ClientSocket.ReceiveTimeout = 10000; networkStream.ReadTimeout = 10000; StreamReader sr = new StreamReader(networkStream); StreamWriter sw = new StreamWriter(networkStream); sw.AutoFlush = true; while (this._sharedState.ContinueProcess) { if ((DateTime.Now - this.LastPing).TotalMilliseconds > 30000) { break; } //if we have pending message in the queue, send it here if (this._messageQueue.Count != 0) { var message = this._messageQueue.Dequeue(); sw.WriteLine(message); } bytes = new byte[this.ClientSocket.ReceiveBufferSize]; try { data = sr.ReadLine(); if (data != null) { // Show the data on the console. Debug.WriteLine("Text received : {0}", data); //if we got a PING message, reply with PONG. This is the heartbeat function. if (data == "PING") { sw.WriteLine("PONG"); this.LastPing = DateTime.Now; } else { this.RaiseMessageReceive(data); } } } catch (IOException ex) { Debug.WriteLine("StealME.Message: Timeout"); } // Timeout catch (SocketException) { Debug.WriteLine("Connection is broken!"); break; } } networkStream.Close(); this.ClientSocket.Close(); } this.RaiseDisconnected(); // Signal main process if this is the last Client connections main thread requested to stop. if (!this._sharedState.ContinueProcess && this._sharedState.NumberOfClients == 0) this._sharedState.Ev.Set(); }