/// <summary> /// 添加新客户 /// </summary> /// <param name="acceptEventArgs"></param> private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { if (acceptEventArgs.AcceptSocket.RemoteEndPoint == null) { throw new Exception("服务器停止."); } DelegateState.ServerStateInfo(" TCP - 客户端:" + acceptEventArgs.AcceptSocket.RemoteEndPoint + "连接"); DelegateState.ServerConnStateInfo(acceptEventArgs.AcceptSocket.RemoteEndPoint.ToString(), "TCP"); SocketUserToken userToken = m_asyncSocketUserTokenPool.Pop(); m_asyncSocketUserList.Add(userToken); userToken.ConnectSocket = acceptEventArgs.AcceptSocket; userToken.ConnectDateTime = DateTime.Now; try { bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs);//异步回调函数确定 if (!willRaiseEvent) { lock (userToken) { ProcessReceive(userToken.ReceiveEventArgs); } } } catch (Exception e) { DelegateState.ServerStateInfo("连接端 " + userToken.ConnectSocket + " 错误, 错误信息: " + e.Message); } StartAccept(acceptEventArgs);//递归继续异步监控客户端 }
/// <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(); }