【问题标题】:C# - System.Timers synchronization issueC# - System.Timers 同步问题
【发布时间】:2014-02-14 15:56:51
【问题描述】:

我目前正在使用 UDP 协议在 C# 中制作远程管理工具。

因为 UDP 是无连接的,所以我让客户端每秒发送一个 Keep-Alive 数据包,而在服务器端,每次客户端连接时,都会为新客户端创建一个新的计时器,间隔为 2秒(如果 2 秒后没有收到来自客户端的数据包,则客户端超时并被视为断开连接)。

现在,问题是,当我连接多个用户时,只有当第一个用户断开连接时,服务器才会检测到这一点。当其他用户继续超时并断开连接时,服务器不会注意到,似乎客户端仍然连接。

至于客户端对象——每个客户端都有一个定时器参数,每次创建客户端对象时都会使用构造函数自动创建。

userID变量是Form中的一个类变量,用来统计总连接用户数。

这是服务器端代码:

        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";
    }

客户端代码并不重要 - Keep-Alive 只是每秒发送一个数据包。

那么,为什么服务器只检测到第一次断开连接?

我尝试使用计时器更改几项内容,但没有成功。

你们有什么想法吗?

【问题讨论】:

    标签: .net multithreading sockets networking timer


    【解决方案1】:

    如果 userId 始终相同怎么办?

    【讨论】:

    • 哇,真不敢相信我错过了这样的事情。非常感谢!
    猜你喜欢
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    相关资源
    最近更新 更多