/// <summary> /// 向单个客户端发送数据 /// </summary> /// <param name="rsClient"></param> /// <param name="data"></param> public void SendData(RegistryClient registryClient, RegistryMessageAction action, String data) { try { RegistryMessage rm = new RegistryMessage() { Action = action, MessageBody = data }; String messageData = XmlUtil.SaveXmlFromObj <RegistryMessage>(rm); Console.WriteLine("发送数据:{0}", messageData); Byte[] msg = Encoding.UTF8.GetBytes(messageData); registryClient.Socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(SendCallback), registryClient); } catch (Exception ex) { XTrace.WriteLine("发送数据时发生异常:" + ex.ToString()); lock (m_RegistryClients) { m_RegistryClients.Remove(registryClient); registryClient.Dispose(); } } }
/// <summary> /// 接收请求回调函数 /// </summary> /// <param name="ar"></param> private void ReceiveCallback(IAsyncResult ar) { RegistryClient registryClient = (RegistryClient)ar.AsyncState; try { int dataLength = registryClient.Socket.EndReceive(ar); if (dataLength == 0) { Console.WriteLine("接收客户端:{0}已经断开连接。", registryClient.ClientIP); lock (m_RegistryClients){ m_RegistryClients.Remove(registryClient); registryClient.Dispose(); } } else { String data = Encoding.UTF8.GetString(registryClient.ReceiveBuffer, 0, dataLength); Console.WriteLine("接收客户端:{0}发送的数据:{1}。", registryClient.ClientIP, data); //--解析来自客户端的类型 CometMessage regMessage = XmlUtil.LoadObjFromXML <CometMessage>(data); registryClient.RegistryClientType = regMessage.ClientType; registryClient.ClientVersion = regMessage.ClientVersion; registryClient.ClearBuffer(); registryClient.Socket.BeginReceive(registryClient.ReceiveBuffer, 0, registryClient.ReceiveBuffer.Length , SocketFlags.None, new AsyncCallback(ReceiveCallback), registryClient); //--由消息处理器进行处理 m_MessageProcessor.Process(registryClient, regMessage); }; } catch (Exception ex) { XTrace.WriteLine("接收数据时发生异常:" + ex.ToString()); lock (m_RegistryClients) { m_RegistryClients.Remove(registryClient); registryClient.Dispose(); } } }
/// <summary> /// 发送数据回调函数 /// </summary> /// <param name="ar"></param> private void SendCallback(IAsyncResult ar) { RegistryClient registryClient = ar.AsyncState as RegistryClient; try { registryClient.Socket.EndSend(ar); } catch (Exception ex) { XTrace.WriteLine("发送数据时发生异常:" + ex.ToString()); lock (m_RegistryClients) { m_RegistryClients.Remove(registryClient); registryClient.Dispose(); } } }