/// <summary> /// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点 /// </summary> /// <returns></returns> public static PackageManage GetInstance() { // 如果类的实例不存在则创建,否则直接返回 if (uniqueInstance == null) { uniqueInstance = new PackageManage(); } return(uniqueInstance); }
/// <summary> /// 因为客户端只接受来自服务器的数据 /// 因此这个方法中不需要参数 /// </summary> private void ReceiveMessage() { //设置循环标志位 bool flag = true; while (flag) { try { // //获取数据长度 // int receiveLength = clientSocket.Receive(result); // //获取服务器消息 // int iPackageLength = BitConverter.ToInt32(result, 0); // // ByteBuffer buffer = new ByteBuffer(result, iPackageLength); // int iReadLength = buffer.ReadInt(); // int iProtocol = buffer.ReadInt(); // int iRet = buffer.ReadInt(); // if(0==iRet){ // int iPlayerId = buffer.ReadInt(); // int iGoldNum = buffer.ReadInt(); // char cHeadIndex = buffer.ReadChar(); // string strNickname = buffer.ReadString(iPackageLength); // short sGameRoomId = buffer.ReadShort(); // Debug.Log(string.Format("接收到数据包中的iReadLength={0},iProtocol={1},iRet={2},iPlayerId={3},iGoldNum={4},cHeadIndex={5},strNickname={6},sGameRoomId={7}:", iReadLength, iProtocol, iRet, iPlayerId, iGoldNum, "", strNickname, sGameRoomId)); // Debug.Log("strNickname=" + strNickname); // Debug.Log("sGameRoomId=" + sGameRoomId); // int head = Convert.ToInt16(cHeadIndex); // Debug.Log("cHeadIndex=" + head); // } //接受消息头(4字节) int HeadLength = 4; //存储消息头的所有字节数 byte[] recvBytesHead = new byte[HeadLength]; //如果当前需要接收的字节数大于0,则循环接收 while (HeadLength > 0) { byte[] recvBytes = new byte[4]; //将本次传输已经接收到的字节数置0 int iBytesHead = 0; //如果当前需要接收的字节数大于缓存区大小,则按缓存区大小进行接收,相反则按剩余需要接收的字节数进行接收 if (HeadLength >= recvBytes.Length) { iBytesHead = clientSocket.Receive(recvBytes, recvBytes.Length, 0); } else { iBytesHead = clientSocket.Receive(recvBytes, HeadLength, 0); } //将接收到的字节数保存 recvBytes.CopyTo(recvBytesHead, recvBytesHead.Length - HeadLength); //减去已经接收到的字节数 HeadLength -= iBytesHead; } //接收完整消息 int BodyLength = BitConverter.ToInt32(recvBytesHead, 0) - 4; //存储消息体的所有字节数 byte[] recvBytesBody = new byte[BodyLength]; //如果当前需要接收的字节数大于0,则循环接收 while (BodyLength > 0) { byte[] recvBytes = new byte[BodyLength < 1024 ? BodyLength : 1024]; //将本次传输已经接收到的字节数置0 int iBytesBody = 0; //如果当前需要接收的字节数大于缓存区大小,则按缓存区大小进行接收,相反则按剩余需要接收的字节数进行接收 if (BodyLength >= recvBytes.Length) { iBytesBody = clientSocket.Receive(recvBytes, recvBytes.Length, 0); } else { iBytesBody = clientSocket.Receive(recvBytes, BodyLength, 0); } //将接收到的字节数保存 recvBytes.CopyTo(recvBytesBody, recvBytesBody.Length - BodyLength); //减去已经接收到的字节数 BodyLength -= iBytesBody; } //clientSocket.Receive(recvBytesBody, BodyLength, 0); //一个数据包接收完毕,解析数据体 //UnpackData(recvBytesBody); PackageManage.GetInstance().UnpackData(recvBytesBody); } catch (Exception e) { //停止消息接收 flag = false; //断开服务器 clientSocket.Shutdown(SocketShutdown.Both); //关闭套接字 clientSocket.Close(); SocketQuit(); Debug.Log("服务器返回数据:" + e.Message); } _thread_wait(); } }