我目前正在使用UDP协议在C#中制作一个远程管理工具。
因为UDP是无连接的,我让客户端每秒钟发送一个保持活动的数据包,在服务器端,每次客户机连接时,为新客户端创建一个新的计时器,间隔为2秒(如果2秒过去而没有从客户端接收数据包,客户机超时并被视为断开连接)。
现在,问题是,当我连接多个用户时,只有当第一个用户断开连接时,服务器才会检测到这一点。当其他用户继续超时和断开连接时,服务器没有注意到,似乎客户端还在连接。
至于客户端对象-每个客户端都有一个计时器参数,每次创建客户端对象时都会使用构造函数自动创建这个参数。
userID变量是表单中的类变量,它应该计算总连接用户的数量。
以下是服务器端代码:
void Receive()
{
while (true)
{
bool pass = true;
byte[] msg = new byte[1024];
IPEndPoint Sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)Sender;
try { server.ReceiveFrom(msg, ref Remote); }
catch { pass = false; }
if (pass)
{
Thread handle = new Thread(() => HandleInput(msg, Remote));
handle.Start();
}
}
}
void HandleInput(byte[] msg, EndPoint Remote)
{
string data = Encoding.ASCII.GetString(msg);
data = data.Replace("\0", "");
if (data.Contains("Connect!"))
{
clients.Add(new Client(Remote, userID));
clients[userID].timer.Elapsed += (sender, e) => Timeout(sender, e, clients[userID-1]);
clients[userID].timer.Enabled = true;
listBox1.Items.Add(Remote.ToString());
userID++;
}
for (int i = 0; i < clients.Count; i++)
{
if (EndPoint.Equals(clients[i].Remote, Remote))
{
clients[i].timer.Interval = 2000;
}
}
}
void Timeout(object source, ElapsedEventArgs e, Client user)
{
listBox1.Items.Remove(user.Remote.ToString());
label2.Text = user.Remote.ToString() + " Disconnected";
}客户端代码并不是真正重要的-保持活着-那里只有一个数据包被发送每秒钟。
那么,为什么服务器只检测到第一次断开连接呢?
我试过用计时器换几样东西,但没有运气。
你们知道吗?
发布于 2014-02-14 16:02:28
如果userId总是一样的话呢?
https://stackoverflow.com/questions/21783810
复制相似问题