Answer the question
In order to leave comments, you need to log in
Can anyone rate the code for a client-server chat based on tcp/ip?
Server - https://github.com/SuperDru/TcpChatServer.git
Client - https://github.com/SuperDru/TcpChatClient.git
I'm learning c#, it's quite difficult to figure out what exactly I'm doing wrong and don't want to write the following project making the same mistakes without being aware of it, so any constructive comments on the code would be greatly appreciated.
Answer the question
In order to leave comments, you need to log in
You can talk about client-server applications for a long time. I will dwell on only one aspect: how to make sure that this server does not lie down.
The solutions that you have applied will work well with a load of 1 person (since we cannot press buttons in two windows at the same time), but already 2-3 people can easily put down a server if they start sending messages often.
In this regard, a few wishes:
In the connection waiting loop, we make a call to AcceptTcpClient():
In this case, we can easily get a network exception related to the inability to connect a particular client. And our server will go down. Because of one single unsuccessful connection of the client (maybe his Internet has fallen off). And the server should continue to work. To do this, it makes sense to wrap the call to AcceptTcpClient () in a try-catch, log the exception and continue working.
try
{
ServerClient client = new ServerClient(server.AcceptTcpClient());
// ...
}
catch (Exception e) when (server.Active)
{
// Логируем исключение и продолжаем работу
// (если сервер не остановлен).
}
clients.Add()
clients.ForEach()
clients.TrueForAll()
clients.Remove()
public static class Server
{
public static object State = new object();
public static void Listen(string ip)
{
//...
// Кстати, цикл имеет смысл прервать, если сервер будет остановлен через Stop()
while (server.Active)
{
//...
lock(State)
{
clients.Add(client);
}
}
}
}
public class ServerClient
{
private void RemoveUser()
{
lock(Server.State)
{
Server.clients.Remove(this);
Server.users = Server.users.Replace(name + "\n", "");
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question