look i am trying to make a TCP server for a private chatroom with AES encryption.
but the problem i am facing is that when one client joins it works fine. but when two join it become odd like a new client would join even tho they are only two clients connected. i have been trying to fix this but with no luck. also it never sends the message to the client
I beleave the problem is with is function
public static void Brodcast_Message(TcpClient tcp, string message)
{
for(int i = 0; i < clients.Count; i++)
{
if(tcp != clients[i])
{
Console.WriteLine(clients[i].Connected);
if (clients[i].Connected)
{
byte[] buffer = Encoding.ASCII.GetBytes(message);
Stream stream = clients[i].GetStream();
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
Console.WriteLine($"Send Message: {message}");
}
else
{
clients.RemoveAt(i);
threads[i].Abort();
threads.RemoveAt(i);
Console.WriteLine("Client Disconnected");
}
}
}
}
this is what "threads" and "clients" are
public static List<TcpClient> clients = new List<TcpClient>();
public static List<Thread> threads = new List<Thread>();
this is the client thread
public static void Client_Thread(TcpClient client)
{
bool exit = true;
while (exit)
{
try
{
byte[] buffer = new byte[500];
Stream stream = client.GetStream();
stream.Read(buffer, 0, buffer.Length);
string messsage = Encoding.ASCII.GetString(buffer).Replace("\0", "");
if (!String.IsNullOrEmpty(messsage))
{
Console.WriteLine($"MSG: {messsage}");
Brodcast_Message(client, messsage);
}
}
catch (Exception) { exit = false; }
}
}
this is the starting point
static void Main(string[] args)
{
listener.Start(100);
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Thread thread = new Thread(() => Client_Thread(client));
clients.Add(client);
threads.Add(thread);
Console.WriteLine("Client Connected");
thread.Start();
}
}
as for the client
public static void Server_Thread(ListBox Users, ListBox Messages)
{
while (true)
{
try
{
client = new TcpClient("127.0.0.1", 2355);
while (true)
{
Stream sw = client.GetStream();
byte[] buffer = new byte[500];
sw.Read(buffer, 0, buffer.Length);
string encoded_data = Decrypt(Encoding.ASCII.GetString(buffer), "YOUR_PASSWORD");
MessageBox.Show(encoded_data);
string[] data = encoded_data.Split(':');
if (!String.IsNullOrEmpty(encoded_data))
{
if (!User_Check(data[0], Users))
{
Users.Invoke((MethodInvoker)delegate { Users.Items.Add(data[0]); });
}
else if (data[0] == "SYSTEM")
{
Users.Invoke((MethodInvoker)delegate { Users.Items.Remove(data[1]); });
}
else
{
Messages.Invoke((MethodInvoker)delegate { Messages.Items.Add($"{data[0]} >> {data[1]}"); });
}
}
}
}
catch (Exception) { }
}
}
What I have tried:
i have tried googling and i have tired changing some of the functions but again with no luck. if you know the how to fix this problem i would very much like to know. anyway i have changing code on the client and the server and with no provail.