【发布时间】:2014-12-13 18:13:48
【问题描述】:
下面是一段代码。我正在尝试分别处理上游和下游。但不幸的是,handleUpStream() 永远不会在handleDownStream 之后发生。
如果我删除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;
}
}
【问题讨论】:
-
如果您的代码从未进入某个位置,则意味着它在该位置之前停止。使用调试器单步执行此代码以找出位置。
-
您是否尝试逐步检查以确保 networkstream.Read 不会以某种方式阻碍您?另外,在阅读之前可能需要检查
CanRead(msdn.microsoft.com/en-us/library/…)。
标签: c# multithreading sockets