I’m making a basic C# TCP Console Server that accepts connections from 2 different clients. After that the server needs to be able to receive messages from the two clients after they have connected, this should be able to go on until the connection has been terminated.
So far I can send messages to the clients, but I’m in trouble with having two clients getting to talk to the server at once. I’m pretty sure I just have to add some threads in here but I’m new to it so I’m not sure how to get it working. That’s where I need assistance.
string str1 = "";
string str2 = "";
Socket soc1;
Socket soc2;
NetworkStream straumur1;
NetworkStream straumur2;
BinaryReader lesari1;
BinaryReader lesari2;
BinaryWriter skrifari1;
BinaryWriter skrifari2;
IPAddress ipTala = IPAddress.Parse("127.0.0.1");
TcpListener hlustari = new TcpListener(ipTala, 50000);
Lesa lesa = new Lesa();
hlustari.Start();
//Notandi 1 tengist
soc1 = hlustari.AcceptSocket();
straumur1 = new NetworkStream(soc1);
skrifari1 = new BinaryWriter(straumur1);
lesari1 = new BinaryReader(straumur1);
skrifari1.Write("Leikmaður 1");
Console.WriteLine(">> Leikmaður 1 tengdist");
//Notnadi 2 tengist
soc2 = hlustari.AcceptSocket();
straumur2 = new NetworkStream(soc2);
skrifari2 = new BinaryWriter(straumur2);
lesari2 = new BinaryReader(straumur2);
skrifari2.Write("Leikmaður 2");
Console.WriteLine(">> Leikmaður 2 tengdist");
do //this is the part that needs fixing.
{
str1 = lesari1.ReadString();
skrifari1.Write(str1);
Console.WriteLine(str1);
} while (true);
do
{
str2 = lesari2.ReadString();
skrifari2.Write(str2);
Console.WriteLine(str2);
} while (true);
You’ve blocked the execution flow by infinite looping with the first BinaryReader. A simple apporoach would be looping them in different threads, and from the main thread, waiting both. I don’t have access to Visual Studio right now, but something like this might work:
Again, I’m not sure if there are any typos or naming errors, but something like this would do the trick. Also, whenever you access shared data (an object that you can access from both threads), be careful not to have any race conditions. This is a wonderful tutorial/resource for .NET threading: http://www.albahari.com/threading/