我正在制作一个基本的 C# TCP 控制台服务器,它接受来自 2 个不同客户端的连接。之后,服务器需要能够在两个客户端连接后接收来自它们的消息,这应该能够持续到连接终止。到目前为止,我可以向客户端发送消息,但是我遇到了让两个客户端同时与服务器通信的问题。我很确定我只需要在这里添加一些线程,但我是新手,所以我不确定如何让它工作。这就是我需要帮助的地方。
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);