public void DaemonThreadStart() { while (m_thread.IsAlive) { SocketUserUDP[] userUDPArray = new SocketUserUDP[m_asyncudpServer.DeviceInfoList.Count]; m_asyncudpServer.DeviceInfoList.CopyTo(userUDPArray); for (int i = 0; i < userUDPArray.Length; i++) { if (!m_thread.IsAlive) { break; } try { if ((DateTime.Now - userUDPArray[i].ActiveDateTime).Milliseconds > m_asyncudpServer.socketTimeoutMs) { lock (userUDPArray[i]) { m_asyncudpServer.DeviceInfoList.Remove(userUDPArray[i]); } } for (int x = 0; x < 60 * 1000 / 10; x++) //每十分钟检测一次 { if (!m_thread.IsAlive) { break; } Thread.Sleep(100); } TeartbeatCount++; DelegateState.ServerStateInfo("UDP:" + TeartbeatCount + "心跳检测"); } catch (Exception ex) { DelegateState.ServerStateInfo("Error:类[DaemonThreadUDP]" + ex.Message); } } } }
/// <summary> /// 监控 /// </summary> public void StartAccept() { //异步操作 //m_sListen.BeginReceiveFrom( //m_sListen.Buffer, 0, state.Buffer.Length, //m_sListen.None, //ref m_sListen.RemoteEP, //EndReceiveFromCallback, //state); m_sListen.ReceiveFrom(BufferData, ref RemoteEndPoint); semap.WaitOne(); if (BufferData[0] == 0x1) { string username = Encoding.UTF8.GetString(BufferData, 1, BufferData.Length); SocketUserUDP userUdp = new SocketUserUDP(); userUdp.ipEndPoint = RemoteEndPoint; userUdp.ActiveDateTime = DateTime.Now; userUdp.UserName = username; userUdp.password = username; if (userUdp.password.Length > 4) { //密码小于4是设备 DeviceInfoList.Add(userUdp); DelegateState.ServerStateInfo(RemoteEndPoint.ToString() + "远端设备连接"); } else { UserInfoList.Add(userUdp); DelegateState.ServerStateInfo(RemoteEndPoint.ToString() + "远端用户连接"); } m_sListen.SendTo(Encoding.UTF8.GetBytes("连接成功!"), RemoteEndPoint); DelegateState.ServerConnStateInfo(RemoteEndPoint.ToString(), "UDP"); } else if (BufferData[0] == 0x2) { string username = Encoding.UTF8.GetString(BufferData, 1, BufferData.Length); foreach (SocketUserUDP user in DeviceInfoList) { if (user.UserName == username) { user.ActiveDateTime = DateTime.Now; m_sListen.SendTo(Encoding.UTF8.GetBytes(user.ipEndPoint.ToString()), RemoteEndPoint); DelegateState.ServerStateInfo(RemoteEndPoint.ToString() + "远端用户:" + user.UserName + "搜索设备."); } } } else if (BufferData[0] == 0x3) { string username = Encoding.UTF8.GetString(BufferData, 1, BufferData.Length); foreach (SocketUserUDP user in UserInfoList) { if (user.UserName == username) { DeviceInfoList.Remove(user); DelegateState.ServerStateInfo("UDP:" + RemoteEndPoint.ToString() + "远端用户退出"); break; } } } else { DelegateState.ServerStateInfo("UDP:" + RemoteEndPoint.ToString() + "发送空数据"); } semap.Release(); StartAccept(); }