日期:2014-05-18 浏览次数:21197 次
/// <summary> /// 基础协议 /// </summary> /// <param name="name">协议名称</param> /// <param name="command">命令类型[枚举]</param> /// <param name="protocol">网络协议类型[枚举]</param> /// <param name="packageBody">消息包体</param> /// <param name="isNeedReturn">是否需要回馈[枚举]</param> /// <param name="isNeedEncrypt">是否加密[枚举]</param> /// <param name="sessionCode">会话码</param> /// <returns></returns> public static byte[] GetProtocol(String name, int command, int protocol, byte[] packageBody, Return isNeedReturn, Encrypt isNeedEncrypt, String sessionCode) { byte[] p1 = Encoding.Default.GetBytes(name); byte[] p2 = Encoding.Default.GetBytes(command.ToString()); byte[] p3 = Encoding.Default.GetBytes(protocol.ToString()); byte[] p4 = packageBody; byte[] p5 = Encoding.Default.GetBytes(isNeedReturn.ToString()); byte[] p6 = Encoding.Default.GetBytes(isNeedEncrypt.ToString()); //这里我把decollator作为的一个分隔符 byte[] decollator = Encoding.Default.GetBytes("≮?≯"); byte[] result = new byte[p1.Length + p2.Length + p3.Length + p4.Length + p5.Length + p6.Length]; Array.Copy(p1, 0, result, 0, p1.Length); Array.Copy(decollator, 0, result, p1.Length, decollator.Length); Array.Copy(p2, 0, result, p1.Length + decollator.Length, p2.Length); Array.Copy(decollator, 0, result, p1.Length + p2.Length + decollator.Length, decollator.Length); Array.Copy(p3, 0, result, p1.Length + p2.Length + decollator.Length * 2, p3.Length); Array.Copy(decollator, 0, result, p1.Length + p2.Length + p3.Length + decollator.Length * 2, decollator.Length); Array.Copy(p4, 0, result, p1.Length + p2.Length + p3.Length + decollator.Length * 3, p4.Length); Array.Copy(decollator, 0, result, p1.Length + p2.Length + p3.Length + p4.Length + decollator.Length * 3, decollator.Length); Array.Copy(p5, 0, result, p1.Length + p2.Length + p3.Length + p4.Length + decollator.Length * 4, p5.Length); Array.Copy(decollator, 0, result, p1.Length + p2.Length + p3.Length + p4.Length + p5.Length + decollator.Length * 4, decollator.Length); Array.Copy(p6, 0, result, p1.Length + p2.Length + p3.Length + p4.Length + p5.Length + decollator.Length * 5, p6.Length); return result; }
static void Main(string[] args) { Dictionary<string, string> dics = new Dictionary<string, string>(); dics.Add("username", "007"); dics.Add("password", "@#$"); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000)); JavaScriptSerializer jss = new JavaScriptSerializer(); string s = jss.Serialize(dics); socket.Send(Encoding.UTF8.GetBytes(s.ToString())); socket.Close(); }
------解决方案--------------------
证明json之类的协议的性能要比xml等不快很多倍 --> 证明json之类的协议的性能要比xml等不知快了很多倍
json比xml快很多倍。现在的计算机非常快,使用json传送命令是非常合适的。用不着搞一大堆“啊~~~~呀~~~~咿咿呀呀~~~~~”的莫名其妙的二进制格式,然后你自己再写一大堆缓慢的所谓解析。
------解决方案--------------------