StreamReader.ReadLine 在 2 个客户端发送时挂起
StreamReader.ReadLine is hanging when 2 clients are sending
我在做一个实验,我有一个 streamreader 和 2 个 TcpClients streamreader 继续从客户端 1 读取并且从不从客户端 2 读取,直到客户端 1 发送一些东西
因此,如果客户端 1 从未发送任何内容,streamreader 将永远不会从客户端 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);
}
}
}
(客户端是一个class来保存streamreader并写入)
为每个客户端提供一个单独的线程,尝试以下方法:
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)) );
}
我在做一个实验,我有一个 streamreader 和 2 个 TcpClients streamreader 继续从客户端 1 读取并且从不从客户端 2 读取,直到客户端 1 发送一些东西 因此,如果客户端 1 从未发送任何内容,streamreader 将永远不会从客户端 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);
}
}
}
(客户端是一个class来保存streamreader并写入)
为每个客户端提供一个单独的线程,尝试以下方法:
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)) );
}