以下是代码段。我试图分别处理上游和下游。但遗憾的是,在handleDownStream之后,handleUpStream()永远不会发生。
如果我删除handleDownStream,那么handleupstream的一切都很好。我在handleDownStream中缺少一些东西,我不知道是什么。
public void run()
{
while (running)
{
if (ClientPool == null)
continue;
foreach (Client c in ClientPool)
{
NetworkStream networkStream = c.getTcpClient().GetStream();
handleDownStream(c, networkStream);
handleUpstream(c, networkStream);
}
}
}
public void handleDownStream(Client c, NetworkStream networkstream)
{
try
{
networkstream.Read(bytesFrom, 0, (int)c.getTcpClient().ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
Console.WriteLine("Message From: " + c.getClientIp() + " : " + dataFromClient);
dataFromClient = null;
bytesFrom = new byte[10025];
}
catch (Exception e)
{
// I tried to see if there was some sort of exception here that was a silent killer.
Console.WriteLine(e.ToString());
return;
}
}
public void handleUpstream(Client c, NetworkStream networkstream)
{
// The below never happens.
Console.WriteLine("this lol");
if (c.getTimeSinceLastMessage() > 30000 && c.getPinged())
{
Console.WriteLine("Removing Client From Pool, " + c.getClientIp());
removeClientFromPool(c);
return;
}
if (c.getTimeSinceLastMessage() > 15000 && c.getPinged() == false)
{
Console.WriteLine("Sending ping to Client, " + c.getClientIp());
c.switchPinged();
bytesToSend = Encoding.ASCII.GetBytes("ping");
networkstream.Write(bytesToSend, 0, bytesToSend.Length);
networkstream.Flush();
bytesToSend = null;
}
}
答案 0 :(得分:0)
这是令人尴尬的......
除了检查它之外,您还可以阅读,您需要检查是否有数据可供阅读...对于那些像我这样的新人或忘记在这里检查更新的代码。很明显,如果你调用networkstream.read(),它会等待一条消息(它与该线程同步)。
以下是需要查看发生情况的修订工作代码。
public void run()
{
while (running)
{
if (ClientPool == null)
continue;
foreach (Client c in ClientPool)
{
NetworkStream networkStream = c.getTcpClient().GetStream();
if (networkStream.CanRead)
handleDownStream(c, networkStream);
handleUpstream(c, networkStream);
}
}
}
public void handleDownStream(Client c, NetworkStream networkstream)
{
if (networkstream.DataAvailable == false)
return;
try
{
networkstream.Read(bytesFrom, 0, (int)c.getTcpClient().ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
Console.WriteLine("Message From: " + c.getClientIp() + " : " + dataFromClient);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return;
}
}
public void handleUpstream(Client c, NetworkStream networkstream)
{
if (c.getTimeSinceLastMessage() > 30000 && c.getPinged())
{
Console.WriteLine("Removing Client From Pool, " + c.getClientIp());
removeClientFromPool(c);
return;
}
if (c.getTimeSinceLastMessage() > 15000 && c.getPinged() == false)
{
Console.WriteLine("Sending ping to Client, " + c.getClientIp());
c.switchPinged();
bytesToSend = Encoding.ASCII.GetBytes("ping");
networkstream.Write(bytesToSend, 0, bytesToSend.Length);
networkstream.Flush();
bytesToSend = null;
}
}