I'm trying to create C# console app.It's like public chat with multiples clients.Everything works fine I just try to understand how I can know when somebody goes offline.App is work with TCPListener
and TCPClient
.So on the server side I wrote some code which trying to detect who is offline.I'm not sure but i'm thinking the problem is in TCPListener because when he waiting a new connection software is freezed and can't continue loop.
Server code:
string clientUsername = string.Empty;
IPAddress ip = IPAddress.Parse("192.168.1.2");
int port = 5555;
TcpListener tcpServer = new TcpListener(ip,port);
tcpServer.Start();
int clientCounter = 0;
List<TcpClient> tcpClients = new List<TcpClient>();
while (true)
{
tcpClients.Add(tcpServer.AcceptTcpClient());
NetworkStream networkStream = tcpClients[clientCounter].GetStream();
BinaryReader readUsername = new BinaryReader(networkStream);
clientUsername = readUsername.ReadString();
if (tcpClients[clientCounter].Connected)
{
Console.WriteLine("Client " + clientUsername + " connected!");
clientCounter++;
}
foreach (TcpClient client in tcpClients)
{
if (!client.Connected)
{
Console.WriteLine("Client " + clientUsername + " is offline!");
}
}
if (tcpClients.Count >= 3)
{
for (int i = 0; i < tcpClients.Count; i++)
{
NetworkStream stream = tcpClients[i].GetStream();
BinaryWriter writer = new BinaryWriter(stream);
writer.Write("Server sending message to every client!");
}
}
}
Client code:
IPAddress ip = IPAddress.Parse("192.168.1.2");
int port = 5555;
TcpClient client = new TcpClient();
client.Connect(ip,port);
NetworkStream networkStream = client.GetStream();
BinaryWriter sendUsername = new BinaryWriter(networkStream);
sendUsername.Write(Environment.UserName);
while (true)
{
NetworkStream stream = client.GetStream();
BinaryReader reader = new BinaryReader(stream);
string messageFromServer = reader.ReadString();
Console.WriteLine(messageFromServer);
}