String data = (buffer, 0, byte_count) Ĭ(SocketShutdown.Both) NetworkStream stream = client.GetStream() Lock (_lock) list_clients.Add(count, client) Static readonly Dictionary list_clients = new Dictionary() Static readonly object _lock = new object()
#Multi chat client windows code#
Here is a version of your code that addresses these two issues: Because you may receive as little as a single byte in a single read operation, even after the user provides input, you may still not receive the complete message that was sent previously.It is not possible to receive data from another client until the next time the user provides some input.This can result in at least a couple of problems: Your client code attempts to process the user input and writes to the server in the same thread that is handling receiving data from the server.This would cause problems for any client-serving thread that is trying to read it concurrently. Meaning that during the course of adding an item, the dictionary may temporarily be in an invalid state. You do not access your dictionary in a thread-safe way, which means that the listening thread, which may add items to the dictionary, can operate on the object at the same time that a client-serving thread is trying to examine the dictionary.However, inspection of the code reveals two significant problems: It is not clear from your question what problems specifically it is you are having. Int byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length) Īrray.Copy(receivedBytes, formated, byte_count) Ĭonsole.WriteLine("disconnect from server!!") IPAddress ip = IPAddress.Parse("127.0.0.1") īyte buffer = (s) I created this box, so I can pass 2 args for the Thread.start(). Public static void broadcast(Dictionary conexoes, string data)īyte buffer = (data) handle the null characteres in the byte arrayĪrray.Copy(buffer, formated, byte_count) Int byte_count = stream.Read(buffer, 0, buffer.Length) NetworkStream stream = box.c.GetStream() Public static void handle_clients(object o) TcpClient client = ServerSocket.AcceptTcpClient() Ĭonsole.WriteLine("Someone connected!!") TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000) When there is 1 client connected, it works as expected, the problem is occurred when there is more than 1 client connected.ĭictionary list_clients = new Dictionary () So, I decided to make a TCP chat, the basic idea is that A client send data to the server, then the server broadcast it for all the clients online (in this case all the clients are in a dictionary).