-1

我正在制作一个基本的 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);
4

1 回答 1

0

您已经通过使用第一个 BinaryReader 进行无限循环来阻止执行流程。一个简单的方法是将它们循环到不同的线程中,并从主线程中等待两者。我现在无法访问 Visual Studio,但这样的事情可能会起作用:

//create the threads with an anonymous method (you may extract them to named methods, if you prefer)
Thread t1 = new Thread(new ThreadStart(()=>{
    do //this is the part that needs fixing.
        {
            str1 = lesari1.ReadString();
            Console.WriteLine(str1);
        } while (true);
    }
   ));

 Thread t2 = new Thread(new ThreadStart(()=>{
    do //this is the part that needs fixing.
        {
            str2 = lesari2.ReadString();
            Console.WriteLine(str2);
        } while (true);
    }
   ));

  t1.Start(); //start threads
  t2.Start();
  t1.Join(); //wait for them to finish
  t2.Join();

同样,我不确定是否有任何拼写错误或命名错误,但这样的事情就可以解决问题。此外,每当您访问共享数据(您可以从两个线程访问的对象)时,请注意不要有任何竞争条件。这是 .NET 线程的精彩教程/资源:http ://www.albahari.com/threading/

于 2012-12-01T13:25:01.103 回答