public TcpChatClient(TcpClient tcpClient, TcpChatServer tcpServer) { this.id = Guid.NewGuid(); this.client = tcpClient; this.stream = client.GetStream(); this.server = tcpServer; this.port = ((IPEndPoint)client.Client.RemoteEndPoint).Port; this.connectionThread = new Thread(new ThreadStart(this.Process)); this.connectionThread.Start(); }
static void Main(string[] args) { TcpChatServer server = new TcpChatServer(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)); Thread listenThread = new Thread(new ThreadStart(server.Listen)); string command; try { server.Start(); // server starts listening the connections on $port listenThread.Start(); Console.WriteLine("Listening connections on port {0}", port); while ((command = ReadCommand()) != "exit") { switch (command) { //case "start": // server.Start(); // server starts listening the connections on $port // listenThread.Start(); // //server.AcceptClientsAsync(); // Console.WriteLine("Listening connections on port {0}", port); // break; case "stop": Console.WriteLine("Stopping listener."); server.Stop(); if (listenThread.IsAlive) { listenThread.Abort(); // if all connections are crushing, means that all child threads are aborted too } break; default: Console.WriteLine("Unknown command."); break; } } } catch (Exception ex) { Console.WriteLine("Server has been stopped. Exception: {0}", ex.Message); } finally { Console.WriteLine("Stopping listener."); server.Disconnect(); if (listenThread.IsAlive) { listenThread.Abort(); } } }