当2个客户端发送时,StreamReader.ReadLine挂起

时间:2017-10-31 14:05:43

标签: c# streamreader readline

我正在做一个实验,我有一个streamreader和2个TcpClients streamreader继续从客户端1读取并且从未从客户端2读取,直到客户端1发送一些东西 因此,如果客户端1从未发送任何内容,则流读取器将永远不会从客户端2读取

我已经尝试了很长时间来解决它

       while(true) 
            {
             foreach (Client client in Clients)
                {
                    var sr = client.clientStreamReader;
                    string data;
                    try
                    {
                        if ((data = sr.ReadLine()) != null)
                        {
                             Console.WriteLine(data);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
          }

(客户端是一个保存streamreader并写入的类)

1 个答案:

答案 0 :(得分:2)

使用单独的线程为每个客户提供服务,请尝试以下操作:

void ReadFromClient(Client client)
{
     var sr = client.clientStreamReader;
     string data;
     try
     {
       if ((data = sr.ReadLine()) != null)
       {
          Console.WriteLine(data);
       }
     }
     catch (Exception e)
    {
       Console.WriteLine(e);
    }
}

然后每次启动一个新线程时遍历客户端:

foreach (Client client in Clients)
{
   Task.Factory.StartNew(new Action(() =>  ReadFromClient(client)) );
}
相关问题