简单的心跳包实现

维护通信双方之间的网络连接,判断通信客户是否正常在线!


接受:  
case "Bit":
        string ipAndport = splitString[1].Trim() + ":" + splitString[2].Trim();
        BitUpdate(ipAndport);
        break;
发送:
	private delegate void BitUpdateDele(string ipAndport);
        /// <summary>
        /// 收到Bit包,修改心跳包标志为0
        /// </summary>
        private void BitUpdate(string ipAndport)
        {
            if (lvwUser.InvokeRequired)
            {
                BitUpdateDele d = BitUpdate;
                lvwUser.Invoke(d, ipAndport);
            }
            else
            {
                for (int i = 0; i < lvwUser.Items.Count; i++)
                {
                    if (lvwUser.Items[i].SubItems[1].Text == ipAndport)
                    {
                        lvwUser.Items[i].SubItems[2].Text = "0";
                        break;
                    }
                }
            }
        }
        private delegate void BitDele();
        /// <summary>
        /// 发送Bit包之前,修改心跳包标志,0--1,1++
        /// </summary>
        private void Bit()
        {
            if (lvwUser.InvokeRequired)
            {
                BitDele d = Bit;
                lvwUser.Invoke(d);
            }
            else
            {
                for (int i = 0; i < lvwUser.Items.Count; i++)
                {
                    if (lvwUser.Items[i].SubItems[1].Text != localIp.ToString() + ":" + port.ToString())
                    {
                        string temp = lvwUser.Items[i].SubItems[2].Text;
                        if (temp == "0")
                            lvwUser.Items[i].SubItems[2].Text = "1";
                        else
                        {
                            lvwUser.Items[i].SubItems[2].Text = (int.Parse(temp) + 1).ToString();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 每隔2秒,进行Bit包发送
        /// </summary>
        private void timer1_Tick(object sender, EventArgs e)
        {
            Bit();
            string Bit = "Bit," + localIp.ToString() + "," + port.ToString();
            SendMessage(localIp,Bit);
        }
        /// <summary>
        /// 进行判断,如果心跳包标志大于3时,说明已经离线删除用户
        /// </summary>
        private void BitJudge()
        {
            if (lvwUser.InvokeRequired)
            {
                BitDele d = Bit;
                lvwUser.Invoke(d);
            }
            else
            {
                for (int i = 0; i < lvwUser.Items.Count; i++)
                {
                    string temp = lvwUser.Items[i].SubItems[2].Text;
                    if (int.Parse(temp) > 3)
                        lvwUser.Items.RemoveAt(i);
                }
            }
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            BitJudge();
        }

你可能感兴趣的:(简单的心跳包实现)