我有一个线程,检查用户是否在线
var user = (User)userObj;
if (!IsUserOnline(user)) return;
if (!TryToConnect(user)) return;
var TCP = user.CmdTCP;
Stream stm = TCP.GetStream();
每次都成功完成,但正如我
stm.Write(GetBytes("chk"), 0, 3);
然后
var bb = new byte[1];
try {
stm.Read(bb, 0, 1);
} catch (Exception e) { /*error*/ }
if (bb[0] == CHR_SUCCESS) {
//etc etc
}
如果用户第二次在线,则在读取时没有警告的流读取失败。没有例外,代码不会更进一步。线程停止,程序正常工作。
整线:
var user = (User)userObj;
if (!IsUserOnline(user)) return;
if (!TryToConnect(user)) return;
var TCP = user.CmdTCP;
Stream stm = TCP.GetStream();
try {
stm.Write(GB("chk"), 0, 3);
toLog("refresh::chk sent ;)");
} catch (Exception e) {
#region unable to send packet, online
toLog("\trefresh::" + user.name + " is online (Connected, unable to send packet) " + e.Message);
setUserStatus(user, userStatus.Online);
return;
#endregion
}
var bb = new byte[1];
try {
stm.Read(bb, 0, 1); //<<<<<<<<< here thread just ends, no toLog("..");, no exception
toLog("refresh::got " + (char)bb[0]);
} catch (Exception e) {
#region unable to get packet, online
toLog("\trefresh::" + user.name + " is online (Connected, unable to get packet) " + e.Message);
setUserStatus(user, userStatus.Online);
return;
#endregion
}
if (bb[0] == CHR_SUCCESS) {
try {
stm.Write(GB(toStr(CHR_SSUCCESS)), 0, 1);
toLog("refresh::CHR_SSUCCESS sent ;)");
} catch (Exception e) {
#region unable to send packet 2, online
toLog("\trefresh::" user.name + " is online (Connected, unable to send packet #2) " + e.Message);
setUserStatus(user, userStatus.Online);
return;
#endregion
}
toLog("\trefresh::" + user.name + " is online");
setUserStatus(user, userStatus.Online);
} else {
for (int x = 0; x < 5; x++) {
toLog("\t\trefresh::got wrong answer");
System.Media.SystemSounds.Beep.Play();
Thread.Sleep(500);
}
setUserStatus(user, userStatus.Online);
}
答案 0 :(得分:0)
看起来像你的Read()块,因为没有数据可供读取。点击此处了解更多信息:What are some reasons NetworkStream.Read would hang/block?
如果我是对的,原因是服务器不发送数据。尝试调试服务器,而不是客户端。