/// <summary> /// 读取数据 /// </summary> private void ReadData(int length) { if (_cacheLength + length > _recvCache.Length) { HelperTool.LogError("FGBaseNet.ReadData : 缓冲区溢出"); return; } Array.Copy(_recvBuffer, 0, _recvCache, _cacheLength, length); //把数据写入缓冲区 _cacheLength += length; if (_cacheLength < 8) { HelperTool.LogError("FGBaseNet.ReadData : 缓冲区数据不足8字节,则继续等待接收"); return; } //TODO :解密数据到_dataBuffer Array.Copy(_recvCache, 0, _dataBuffer, _dataLength, _cacheLength); _dataLength += _cacheLength; if (_cacheLength - _dataLength > 0) { //数据未接收完,下次再接收 return; } else { _cacheLength = 0; } //测试 : 输出消息 Debug.Log(Encoding.UTF8.GetString(_dataBuffer, 0, _dataLength)); }
public void Connect() { try { //转换ip地址 IPAddress ipa; if (IPAddress.TryParse(_ip, out ipa)) { _serverInfo = new IPEndPoint(ipa, _port); } else { //转换失败,根据ip获取相关ip地址或ip地址的dns服务器 IPHostEntry iph = Dns.GetHostEntry(_ip); foreach (var item in iph.AddressList) { _serverInfo = new IPEndPoint(item, _port); break; } } _clientSocket = new Socket(_serverInfo.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _clientSocket.BeginConnect(_serverInfo, new System.AsyncCallback(ConnectCallback), _clientSocket); } catch (Exception e) { //断开连接 Quit(); //打印错误日志 HelperTool.LogError("FGBaseNet.Connect : " + e.ToString()); throw; } }
public static T Deserialize <T>(string xmlName) { if (xmlName == string.Empty) { HelperTool.LogError("FGXmlDocument.Deserialize : xml文件名为空"); return(default(T)); } string xmlPath = Application.dataPath + @"\_Xmls\" + xmlName; if (!File.Exists(xmlPath)) { HelperTool.LogError("FGXmlDocument.Deserialize : " + xmlName + "路径不正确"); return(default(T)); } try { using (StreamReader r = new StreamReader(xmlPath)) { XmlSerializer xs = new XmlSerializer(typeof(TestXml)); return((T)xs.Deserialize(r)); } } catch (System.Exception) { HelperTool.LogError("FGXmlDocument.Deserialize : " + xmlName + "序列化失败"); throw; } }
/// <summary> /// 异步接收消息 /// </summary> private void ReceiveAsync() { try { _clientSocket.BeginReceive(_recvBuffer, 0, _recvBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _clientSocket); } catch (Exception e) { HelperTool.LogError("FGBaseNet.ReceiveAsync : " + e.ToString()); throw; } }
/// <summary> /// 将数据写入到缓冲区 /// </summary> private void ReadToBuffer(int start, int length) { try { _dataStream.Read(_buffer, start, length); } catch (Exception) { HelperTool.LogError("FGSerializer.ReadToBuffer : 内存流数据读取错误"); throw; } }
/// <summary> /// 连接回调 /// </summary> private void ConnectCallback(IAsyncResult ar) { try { _clientSocket.EndConnect(ar); if (IsConnect()) { //开始接受消息 ReceiveAsync(); } else { HelperTool.LogError("FGBaseNet.ConnectCallback : Socket 连接失败..."); } } catch (Exception e) { HelperTool.LogError("FGBaseNet.ConnectCallback : " + e.ToString()); throw; } }
/// <summary> /// 接收消息回调 /// </summary> private void ReceiveCallback(IAsyncResult ar) { try { if (_clientSocket == null) { HelperTool.LogError("FGBaseNet.ReceiveCallback : Socket == null"); return; } if (!_clientSocket.Connected) { HelperTool.LogError("FGBaseNet.ReceiveCallback : Socket未连接"); return; } int length = _clientSocket.EndReceive(ar); if (length > 0) { _msgTatalLength += (ulong)length; //读取字节流 ReadData(length); //继续异步接收 _clientSocket.BeginReceive(_recvBuffer, 0, _recvBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _clientSocket); } else { //关闭连接 //进入发送消息和接受消息 //关闭套接字,不允许重用 Quit(); } } catch (Exception) { throw; } }
/// <summary> /// 核心序列化代码 /// </summary> private static void Serialize(FGWrite write, object ob, Type type) { // 基本类型 if (type.IsPrimitive) { if (type.Equals(typeof(int))) { write.Write((int)ob); } else if (type.Equals(typeof(float))) { write.Write((float)ob); } else if (type.Equals(typeof(byte))) { write.Write((byte)ob); } else if (type.Equals(typeof(long))) { write.Write((long)ob); } else { HelperTool.LogError("FGSerializer.Deserialize : 序列化类型不支持"); } return; } // 字符串 if (type.Equals(typeof(string))) { string str = (string)ob; write.Write(str.Length); write.WriteString(str); return; } // 数组 if (type.IsArray) { Array arr = (Array)ob; if (arr != null) { if (arr.Length > 0) { write.Write(arr.Length); Type at = arr.GetValue(0).GetType(); if (at.Equals(typeof(byte)) || at.Equals(typeof(sbyte))) { write.Write((byte[])ob); } else { for (int i = 0; i < arr.Length; i++) { Serialize(write, arr.GetValue(i), at); } } } } return; } // 泛型List if (type.IsGenericType) { Type listType = type.GetGenericArguments()[0]; Type[] types = type.GetInterfaces(); if (Array.IndexOf(types, typeof(IEnumerable)) > -1) { IEnumerable en = ob as IEnumerable; var enumerator = en.GetEnumerator(); int length = 0; while (enumerator.MoveNext()) { length++; } write.Write(length); enumerator = en.GetEnumerator(); while (enumerator.MoveNext()) { Serialize(write, enumerator.Current, listType); } } return; } // 类 FGReflection reflection = new FGReflection(type); foreach (FGSerializeInfo item in reflection.fieldList) { FieldInfo info = item.info; Type t = info.FieldType; Serialize(write, info.GetValue(ob), t); } }
private static object Deserialize(FGReader reader, Type type) { // 基本类型 if (type.IsPrimitive) { return(DeserializePrimitive(reader, type)); } else if (type.Equals(typeof(string))) { return(reader.ReadString()); } /* 自定义特性类反序列化 */ //Dictionary<string, int> lenDict = new Dictionary<string, int>(); //保存 数组长度标志 和 数组 的关系 object ob = Activator.CreateInstance(type, true); FGReflection reflection = new FGReflection(type); foreach (var item in reflection.fieldList) { FieldInfo info = item.info; Type t = info.FieldType; if (t.Equals(typeof(string))) { int length = reader.ReadInt(); if (length > 0) { info.SetValue(ob, reader.ReadString(length)); } else { info.SetValue(ob, reader.ReadString()); } } else { // 数组 if (t.IsArray) { //根据长度记录,序列化 int length = reader.ReadInt(); if (length > 0) { Type at = t.GetElementType(); if (at.Equals(typeof(byte)) || at.Equals(typeof(sbyte))) { byte[] array = reader.ReadBytes(length); info.SetValue(ob, array); } else { Array array = Array.CreateInstance(t.GetElementType(), length); for (int i = 0; i < length; i++) { array.SetValue(Deserialize(reader, at), i); } info.SetValue(ob, array); } } else { HelperTool.LogError("FGSerializer.Deserialize : 反序列化" + type.Name + "失败"); continue; } } // 泛型List else if (t.IsGenericType) { Type listType = t.GetGenericArguments()[0]; Type[] types = t.GetInterfaces(); if (Array.IndexOf(types, typeof(IEnumerable)) > -1) { int length = reader.ReadInt(); Type lsType = typeof(List <>); var makeme = lsType.MakeGenericType(listType); object o = Activator.CreateInstance(makeme); MethodInfo method = o.GetType().GetMethod("Add"); object[] insts = new object[length]; for (int i = 0; i < length; i++) { Object inst = Deserialize(reader, listType); method.Invoke(o, new object[] { inst }); } info.SetValue(ob, o); } } else { //非数组结构直接序列化,如果字段为数组的长度标志,记录下来 info.SetValue(ob, DeserializePrimitive(reader, t)); } } } return(ob); }