/// <summary> /// 异步接收回调函数 /// </summary> /// <param name="ir"></param> private void EndReader(IAsyncResult ir) { SocketUserToken ir_UserToken = ir.AsyncState as SocketUserToken; try { if (ir_UserToken.m_nStream != null) { if (m_tcpClient == null) { ir_UserToken.m_nStream.Close(); ir_UserToken.m_nStream.Dispose(); return; } ir_UserToken.Offset = ir_UserToken.m_nStream.EndRead(ir); byte[] buffer = new byte[ir_UserToken.Offset]; Array.Copy(ir_UserToken.ReceiveBuffer.Buffer, buffer, ir_UserToken.Offset); string tmpStr = Encoding.UTF8.GetString(buffer, 0, ir_UserToken.Offset); if (!m_InDataParser.DecodeProtocolText(tmpStr)) //组装成功则进入 { ir_UserToken.ReceiveBuffer.Clear(ir_UserToken.Offset); //接收完成后清除掉前面的缓存 //组装接收的协议 // DelegateState.ServerStateInfo("信息" + Encoding.UTF8.GetString(buffer));//处理信息 } UserToken.m_nStream.BeginRead(UserToken.ReceiveBuffer.Buffer, 0, UserToken.ReceiveBuffer.Buffer.Length, new AsyncCallback(EndReader), UserToken); } } catch (Exception ex) { DelegateState.ServerStateInfo("接收异常:" + ex.Message); } }
/// <summary> /// 信息组装 /// </summary> /// <param name="protocolText"></param> /// <returns></returns> public bool DecodeProtocolText(string protocolText) { //再次组装前,先清除上一次信息 m_header = ""; m_names.Clear(); m_values.Clear(); int speIndex = protocolText.IndexOf(ProtocolKeys.ReturnWrap); if (speIndex < 0) { return(false); } else { //协议组装 string[] tmpNameValues = protocolText.Split(new string[] { ProtocolKeys.ReturnWrap }, StringSplitOptions.RemoveEmptyEntries); if (tmpNameValues.Length < 2) //每次命令至少包括两行 { return(false); } for (int i = 0; i < tmpNameValues.Length; i++)//解析 { string[] tmpStr = tmpNameValues[i].Split(new string[] { ProtocolKeys.EqualSign }, StringSplitOptions.None); if (tmpStr.Length > 1) //存在等号 { if (tmpStr.Length > 2) //超过两个等号,返回失败 { return(false); } if (tmpStr[0].Equals(ProtocolKeys.Command, StringComparison.CurrentCultureIgnoreCase))//找到命令 { m_command = tmpStr[1]; DelegateState.ServerStateInfo("Command命令:" + m_command); } else { m_names.Add(tmpStr[0].ToLower());//(当多条命令需要一次处理时候,需要) m_values.Add(tmpStr[1]); } } } } return(true); }
/// <summary> /// 监控 /// </summary> public void StartAccept() { m_sListen.ReceiveFrom(BufferData, ref remotePoint); DelegateState.ServerStateInfo(Encoding.UTF8.GetString(BufferData)); StartAccept(); }