private void Send(object st, Type sttype, EnumProtocolType protocoltype) { IntPtr plogin = Marshal.AllocHGlobal(Marshal.SizeOf(st)); Marshal.StructureToPtr(st, plogin, false); byte[] body = new byte[Marshal.SizeOf(st)]; Marshal.Copy(plogin, body, 0, Marshal.SizeOf(st)); Marshal.FreeHGlobal(plogin); HEAD hd = CreateHeaderByProtocolType(protocoltype); hd.len = (short)(8 + body.Length); short crc = (short)((hd.len & 0xff) + ((hd.len >> 8) & 0xff) + hd.messagetype + hd.recvaddr + hd.recvtype + hd.sendaddr + hd.sendtype + hd.version + hd.workflow); for (int i = 0; i < body.Length; i++) { crc += (short)body[i]; } //hd.len = System.Net.IPAddress.HostToNetworkOrder(hd.len); IntPtr phd = Marshal.AllocHGlobal(Marshal.SizeOf(hd)); Marshal.StructureToPtr(hd, phd, false); byte[] protocol = new byte[Marshal.SizeOf(hd) + body.Length + 2]; Marshal.Copy(phd, protocol, 0, Marshal.SizeOf(hd)); Array.Copy(body, 0, protocol, Marshal.SizeOf(hd), body.Length); crc = System.Net.IPAddress.HostToNetworkOrder(crc); protocol[protocol.Length - 2] = (byte)((crc >> 8) & 0xff); protocol[protocol.Length - 1] = (byte)(crc & 0xff); Marshal.FreeHGlobal(phd); m_tcpManager.SendData(protocol); }
/// <summary> /// 摘要:依据协议类型,创建包头 /// </summary> /// <param name="ptype">协议类型</param> /// <returns>协议包包头</returns> private static HEAD CreateHeaderByProtocolType(EnumProtocolType ptype) { HEAD h = new HEAD(); h.flag1 = 0x58; h.flag2 = 0x44; h.messagetype = (byte)ptype; h.version = 0x35; h.workflow = unchecked (workflow++); h.recvaddr = 0; h.recvtype = 0; h.sendaddr = 0; h.sendtype = 0; return(h); }
void m_tcpManager_OnReceiveData(object sender, TcpClientEventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("Len:" + e.DataSize + ",Data:"); for (int i = 0; i < e.DataSize; i++) { sb.Append(e.Data[i].ToString("X2")); } if (OnReceiveData != null) { OnReceiveData(sb.ToString(), null); } IntPtr pdata = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HEAD))); Marshal.Copy(e.Data, 0, pdata, Marshal.SizeOf(typeof(HEAD))); HEAD hd = (HEAD)Marshal.PtrToStructure(pdata, typeof(HEAD)); if (!CheckCRC(e.Data)) { return; } int len = e.Data[3] + e.Data[4] << 8 - 8; byte[] body = new byte[len]; Array.Copy(e.Data, 11, body, 0, len); switch ((EnumProtocolType)hd.messagetype) { case EnumProtocolType.RET_HEART_BEAT: OnReceiveData_HB(body); break; case EnumProtocolType.RET_USER_LOGIN: OnReceiveData_LOGIN(body); break; case EnumProtocolType.RET_SUBSCTIBR_DEV_STATUS: OnReceiveData_SubscribrDevStatus(body); break; case EnumProtocolType.NOTE_DEV_STATUS: OnReceiveData_NoteDevStatus(body); break; case EnumProtocolType.RET_SUBSCTIBR_DEV_CHARGE_STATUS: OnReceiveData_SubscribrDevChargeStatus(body); break; case EnumProtocolType.NOTE_DEV_CHARGE_STATUS: OnReceiveData_NoteDevChargeStatus(body); break; case EnumProtocolType.RET_GET_DEV_CHARGE_INFO: OnReceiveData_GetDevChargeInfo(body); break; case EnumProtocolType.RET_GET_DEV_VERSION: OnReceiveData_GetDevVersion(body); break; default: break; } }