private void SendThread(object o) { List <byte[]> workList = new List <byte[]>(10); while (mSendWork) { if (!mSendWork) { break; } if (mClientSocket == null || !mClientSocket.Connected) { continue; } mSendSemaphore.WaitResource(); if (mSendMsgQueue.Empty()) { continue; } mSendMsgQueue.MoveTo(workList); try { for (int k = 0; k < workList.Count; ++k) { var msgObj = workList[k]; if (mSendWork) { mClientSocket.Send(msgObj, msgObj.Length, SocketFlags.None); } } } catch (ObjectDisposedException e) { ReportSocketClosed(ESocketError.ERROR_1, e.Message); break; } catch (Exception e) { ReportSocketClosed(ESocketError.ERROR_2, e.Message); break; } finally { for (int k = 0; k < workList.Count; ++k) { var msgObj = workList[k]; StreamBufferPool.RecycleBuffer(msgObj); } workList.Clear(); } } if (mStatus == SOCKSTAT.CONNECTED) { mStatus = SOCKSTAT.CLOSED; } }
private void UpdatePacket() { if (!mReceiveMsgQueue.Empty()) { mReceiveMsgQueue.MoveTo(mTempMsgList); try { for (int i = 0; i < mTempMsgList.Count; ++i) { var objMsg = mTempMsgList[i]; if (ReceivePkgHandle != null) { ReceivePkgHandle(objMsg); } } } catch (Exception e) { Logger.LogError("Got the f*****g exception :" + e.Message); } finally { for (int i = 0; i < mTempMsgList.Count; ++i) { StreamBufferPool.RecycleBuffer(mTempMsgList[i]); } mTempMsgList.Clear(); } } }
// Use this for initialization void Start() { sendStreamBuffer = StreamBufferPool.GetStream(1024 * 100, true, false); mReceiveStreamBuffer = StreamBufferPool.GetStream(1024 * 100, false, true); InitData(data); msg = new HjSendMsgDef(1000, data, 1204, 0, 0); }
private void ReceiveThread(object o) { StreamBuffer receiveStreamBuffer = StreamBufferPool.GetStream(mMaxReceiveBuffer, false, true); int bufferCurLen = 0; while (mReceiveWork) { try { if (!mReceiveWork) { break; } if (mClientSocket != null) { int bufferLeftLen = receiveStreamBuffer.size - bufferCurLen; int readLen = mClientSocket.Receive(receiveStreamBuffer.GetBuffer(), bufferCurLen, bufferLeftLen, SocketFlags.None); if (readLen == 0) { throw new ObjectDisposedException("DisposeEX", "receive from server 0 bytes,closed it"); } if (readLen < 0) { throw new Exception("Unknow exception, readLen < 0" + readLen); } bufferCurLen += readLen; DoReceive(receiveStreamBuffer, ref bufferCurLen); if (bufferCurLen == receiveStreamBuffer.size) { throw new Exception("Receive from sever no enough buff size:" + bufferCurLen); } } } catch (ObjectDisposedException e) { ReportSocketClosed(ESocketError.ERROR_3, e.Message); break; } catch (Exception e) { ReportSocketClosed(ESocketError.ERROR_4, e.Message); break; } } StreamBufferPool.RecycleStream(receiveStreamBuffer); if (mStatus == SOCKSTAT.CONNECTED) { mStatus = SOCKSTAT.CLOSED; } }
void InitCSAndLuaPBText() { #if !FOR_GC_TEST Logger.Log("=========================CSAndLuaPBText========================="); #endif XLuaManager.Instance.Startup(); XLuaManager.Instance.SafeDoString(CSAndLuaPBTextLuaScript.text); ForCSCallLua = XLuaManager.Instance.GetLuaEnv().Global.Get <Action <byte[]> >("TestCSEncodeAndLuaDeconde");//映射到一个delgate,要求delegate加到生成列表,否则返回null,建议用法 InitData(data); msSend = StreamBufferPool.GetStream(SENF_BUFFER_LEN, true, true); msRecive = StreamBufferPool.GetStream(REVIVE_BUFFER_LEN, true, true); }
void DeepCopyData(ntf_battle_frame_data source, ntf_battle_frame_data dest) { dest.slot_list[0].cmd_list[0].cmd.UID = source.slot_list[0].cmd_list[0].cmd.UID; dest.slot_list[0].cmd_list[0].cmd.cmd_id = source.slot_list[0].cmd_list[0].cmd.cmd_id; dest.slot_list[0].cmd_list[0].cmd.cmd_data = StreamBufferPool.GetBuffer(DATA_BYTE_LENGTH); for (int i = 0; i < DATA_BYTE_LENGTH; i++) { dest.slot_list[0].cmd_list[0].cmd.cmd_data[i] = source.slot_list[0].cmd_list[0].cmd.cmd_data[i]; } dest.slot_list[0].cmd_list[0].server_frame = source.slot_list[0].cmd_list[0].server_frame; dest.slot_list[0].slot = source.slot_list[0].slot; dest.server_curr_frame = source.server_curr_frame; dest.server_from_slot = source.server_from_slot; dest.server_to_slot = source.server_to_slot; dest.time = source.time; }
public override object DeepCopy(object data) { one_cmd fromData = data as one_cmd; if (fromData == null) { throw new System.ArgumentNullException("data"); } one_cmd toData = ProtoFactory.Get <one_cmd>(); toData.cmd_id = fromData.cmd_id; toData.UID = fromData.UID; toData.cmd_data = StreamBufferPool.DeepCopy(fromData.cmd_data); return(toData); }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing && !Empty()) { lock (mMutex) { for (int i = 0; i < mMessageList.Count; i++) { StreamBufferPool.RecycleBuffer(mMessageList[i]); } mMessageList.Clear(); } } disposedValue = true; } }
private void TestCSEncodeAndLuaDeconde() { #if !FOR_GC_TEST Logger.Log("=========================NewRound========================="); #endif msSend.ResetStream(); ntf_battle_frame_data dataTmp = ProtoFactory.Get <ntf_battle_frame_data>(); ntf_battle_frame_data.one_slot oneSlot = ProtoFactory.Get <ntf_battle_frame_data.one_slot>(); ntf_battle_frame_data.cmd_with_frame cmdWithFrame = ProtoFactory.Get <ntf_battle_frame_data.cmd_with_frame>(); one_cmd oneCmd = ProtoFactory.Get <one_cmd>(); cmdWithFrame.cmd = oneCmd; oneSlot.cmd_list.Add(cmdWithFrame); dataTmp.slot_list.Add(oneSlot); DeepCopyData(data, dataTmp); ProtoBufSerializer.Serialize(msSend.memStream, dataTmp); ProtoFactory.Recycle(dataTmp);//*************回收,很重要 byte[] sendBytes = StreamBufferPool.GetBuffer(msSend, 0, (int)msSend.Position()); #if !FOR_GC_TEST // 打印字节流和数据 Debug.Log("CS send to Lua =================>>>" + sendBytes.Length + " bytes : "); var sb = new StringBuilder(); for (int i = 0; i < sendBytes.Length; i++) { sb.AppendFormat("{0}\t", sendBytes[i]); } Logger.Log(sb.ToString()); PrintData(data); #endif ForCSCallLua(sendBytes); IncreaseData(); StreamBufferPool.RecycleBuffer(sendBytes); }
void OnDestory() { Instance = null; StreamBufferPool.RecycleStream(msSend); StreamBufferPool.RecycleStream(msRecive); }
//protected void ReportSocketClosed(int result, string msg) //{ // if (OnClosed != null) // { // AddNetworkEvt(new HjNetworkEvt(this, result, msg, OnClosed)); // } //} private void ReceiveThread(object o) { StreamBuffer receiveStreamBuffer = StreamBufferPool.GetStream(mMaxReceiveBuffer, false, true); int bufferCurLen = 0; try { while (mReceiveWork) { if (!mReceiveWork) { break; } if (mClientSocket == null) { continue; } //if (!mClientSocket.Connected) { // Logger.LogError("mClientSocket.Connected : "); // continue; //} //if (mClientSocket.Available <= 0) {//收不到东西 // Logger.LogError("mClientSocket.Available : "); // continue; //} //if (mClientSocket.Available > 0) { // if (mClientSocket != null) //{ // 总大小 receiveStreamBuffer.size bufferCurLen当前缓存位置 int bufferLeftLen = receiveStreamBuffer.size - bufferCurLen; // 剩余容量 SocketError socketError; int readLen = mClientSocket.Receive(receiveStreamBuffer.GetBuffer(), bufferCurLen, bufferLeftLen, SocketFlags.None, out socketError); if (readLen == 0) {//什么都没有读到 if (socketError == SocketError.ConnectionReset || socketError == SocketError.ConnectionAborted ) { Logger.LogError("socketError : " + socketError); ReportSocketConnected(ESocketError.ERROR_NEW_11, socketError.ToString()); throw new Exception(" Receive socketError " + socketError.ToString());// 网络链接已经断开 需要重新连接 //continue; } else if (socketError == SocketError.Interrupted) // 主动中断 { Logger.LogError("socketError : " + socketError); continue; } else if (socketError == SocketError.Success) { continue; } else { Logger.LogError("socketError : " + socketError); ReportSocketConnected(ESocketError.ERROR_NEW_11, socketError.ToString()); throw new Exception(" Receive socketError " + socketError.ToString()); //continue; //throw new SocketException((int)socketError);// 网络链接已经断开 需要重新连接 //Logger.LogError("socketError : " + socketError); //string disposeEXError = "receive from server 0 bytes,closed it"; //ReportSocketConnected(ESocketError.ERROR_NEW_10, disposeEXError); //throw new ObjectDisposedException("DisposeEX", disposeEXError);// 网络链接已经断开 需要重新连接 } // string disposeEXError = "receive from server 0 bytes,closed it"; // ReportSocketConnected(ESocketError.ERROR_NEW_10, disposeEXError); //throw new ObjectDisposedException("DisposeEX", disposeEXError);// 网络链接已经断开 需要重新连接 // 主动登出 或者是 网络链接已经断开 需要重新连接 } if (readLen < 0) { throw new Exception("Unknow exception, readLen < 0" + readLen); } bufferCurLen += readLen; DoReceive(receiveStreamBuffer, ref bufferCurLen); if (bufferCurLen == receiveStreamBuffer.size) { throw new Exception("Receive from sever no enough buff size:" + bufferCurLen); } //} } } catch (ObjectDisposedException e) { //ReportSocketConnected(ESocketError.ERROR_NEW_10, e.Message); // 正常网络链接断开 不做处理 UnityEngine.Debug.LogException(e); } catch (SocketException e) { UnityEngine.Debug.Log("e.NativeErrorCode : " + e.NativeErrorCode + " e.SocketErrorCode : " + e.SocketErrorCode); string msg = null; switch (e.NativeErrorCode) { case 10004: // 连接断开 登出 msg = string.Format("{0} 连接断开: error code {1}!", "", e.NativeErrorCode); break; default: //其他错误 msg = e.Message; ReportSocketConnected(ESocketError.ERROR_NEW_11, e.Message); break; } UnityEngine.Debug.LogException(e); } catch (ThreadAbortException e) { ReportSocketConnected(ESocketError.ERROR_NEW_12, e.Message); UnityEngine.Debug.LogException(e); // 按照正常处理 } catch (Exception e) { //ReportSocketConnected(ESocketError.ERROR_NEW_13, e.Message); //UnityEngine.Debug.LogException(e); } finally { StreamBufferPool.RecycleStream(receiveStreamBuffer); if (mStatus == SOCKSTAT.CONNECTED) { mStatus = SOCKSTAT.CLOSED; } } }
protected override void RecycleChildren(one_cmd netData) { StreamBufferPool.RecycleBuffer(netData.cmd_data); }
protected override void DoReceive(StreamBuffer streamBuffer, ref int bufferCurLen) { try { /** for test * String plainStr = "中国"; * byte[] encryptBys = Tea.Tea.encrypt2(System.Text.Encoding.Default.GetBytes(plainStr), Tea.Tea.KEY); * int length = Tea.Tea.byteToShort(encryptBys, 0); * byte[] decodeBys = Tea.Tea.decrypt2(encryptBys, length, 2, Tea.Tea.KEY); * string str = System.Text.Encoding.Default.GetString(decodeBys); * Logger.Log("=================================" + str); **/ // 组包、拆包 byte[] data = streamBuffer.GetBuffer(); int lastStartBufferIndex = 0; // 上一次读取的开始位置 streamBuffer.ResetStream(); while (true) { // 总长度 if (bufferCurLen - lastStartBufferIndex < PACKAGE_HEAD_SIZE) { break; } //short msgLen = BitConverter.ToInt16(data, start); int msgLen = Tea.Tea.byteToShort(data, lastStartBufferIndex); // 消息真正长度 int encodeLen = (msgLen + 7) / 8 * 8; // 消息长度补足8位 if (bufferCurLen - lastStartBufferIndex - PACKAGE_HEAD_SIZE < encodeLen) { break; } // 提取字节流,去掉开头表示长度的4字节 //start += PACKAGE_HEAD_SIZE; // 获取的是缓存 byte[] bytes = streamBuffer.ToArray(lastStartBufferIndex + PACKAGE_HEAD_SIZE, encodeLen); // 当前一条协议的长度 //解密 byte[] decryptContent = Tea.Tea.decryptCopy3(bytes, msgLen, 0, netSecretKey); StreamBufferPool.RecycleBuffer(bytes); //streamBuffer. //将decrpy加入缓存 //StreamBufferPool. //int msgId = Tea.Tea.byteToInt(decryptContent,4); // Logger.Log("C# get msgId : "+ msgId); #if LOG_RECEIVE_BYTES var sb = new System.Text.StringBuilder(); for (int i = 0; i < decryptContent.Length; i++) { sb.AppendFormat("{0}\t", decryptContent[i]); } Logger.Log("HjTcpNetwork receive bytes : " + sb.ToString()); #endif mReceiveMsgQueue.Add(decryptContent); // 下一次组包 lastStartBufferIndex = lastStartBufferIndex + PACKAGE_HEAD_SIZE + encodeLen; } if (lastStartBufferIndex > 0) { bufferCurLen -= lastStartBufferIndex; streamBuffer.CopyFrom(data, lastStartBufferIndex, 0, bufferCurLen); } } catch (Exception ex) { Logger.LogError(string.Format("Tcp receive package err : {0}\n {1}", ex.Message, ex.StackTrace)); } }