/// <summary> /// 打包数据 /// </summary> /// <param name="packageData">被包装数据</param> /// <param name="uId">用户Id</param> /// <param name="msgId">数据Id</param> /// <returns></returns> private byte[] PackageData(byte[] packageData, int uId, int msgId) { byte[] result = null; packageData = ByteUtils.AddDataHead(packageData); // 将数据打包放入MsgHead的body中 var dataHead = MsgFactory.GetMsgHead(uId, msgId, packageData); result = SocketManager.Serialize(dataHead); return(result); }
/// <summary> /// 发送消息 /// </summary> /// <param name="msgList">数据list</param> /// <returns></returns> public bool SendList(List <byte[]> msgList) { if (socket == null || !socket.Connected) { if (string.IsNullOrEmpty(connectingAddress) || connectingPort == 0) { Debug.LogError("请先链接再发送消息"); return(false); } if (!Connect(connectingAddress, connectingPort)) { Debug.LogError("链接失败"); return(false); } } if (msgList == null || msgList.Count == 0) { Debug.Log("数据为空"); return(false); } try { var cbMsg = new byte[0]; // 合并数据 foreach (var msg in msgList) { var addHeadMsg = ByteUtils.AddDataHead(msg); cbMsg = ByteUtils.ConnectByte(cbMsg, addHeadMsg, 0, addHeadMsg.Length); } var asyncSend = socket.BeginSend(cbMsg, 0, cbMsg.Length, SocketFlags.None, (ayResult) => { Debug.Log("发送成功"); }, socket); if (asyncSend == null) { Debug.LogError("发送失败异步发送等待为空"); return(false); } if (asyncSend.AsyncWaitHandle.WaitOne(WaitTime, true)) { return(true); } socket.EndSend(asyncSend); Debug.LogError("发送失败" + asyncSend); } catch (Exception e) { Debug.LogError("发送失败:" + e.Message); } return(false); }
/// <summary> /// 打包数据 /// </summary> /// <param name="packageData">被包装数据</param> /// <param name="uId">用户Id</param> /// <param name="msgId">数据Id</param> /// <returns></returns> private byte[] PackageData(byte[] packageData, int uId, int msgId) { byte[] result = null; // 将数据打包放入MsgHead的body中 var dataHead = new MsgHead() { msgId = msgId, userId = uId, body = ByteUtils.AddDataHead(packageData), }; var stream = new MemoryStream(); Serializer.Serialize(stream, dataHead); result = stream.ToArray(); return(result); }
/// <summary> /// 发送消息 /// </summary> /// <param name="msg">数据msg</param> /// <returns></returns> public bool Send(byte[] msg) { if (socket == null || !socket.Connected) { Debug.LogError("请先链接再发送消息"); return(false); } if (msg == null || msg.Length == 0) { Debug.Log("数据为空"); return(false); } try { // 数据格式化 msg = ByteUtils.AddDataHead(msg); var asyncSend = socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, (ayResult) => { Debug.Log("发送成功"); }, socket); if (asyncSend == null) { Debug.LogError("发送失败异步发送等待为空"); return(false); } if (asyncSend.AsyncWaitHandle.WaitOne(WaitTime, true)) { return(true); } socket.EndSend(asyncSend); Debug.LogError("发送失败" + asyncSend); } catch (Exception e) { Debug.LogError("发送失败:" + e.Message); } return(false); }