public void Read(ByteArray bs)
        {
            signature = bs.ReadStringNull();
            streamVersion = bs.ReadInt();
            unityVersion = bs.ReadStringNull();
            unityRevision = bs.ReadStringNull();
            minimumStreamedBytes = bs.ReadInt();
            headerSize = bs.ReadUInt();

            numberOfLevelsToDownload = bs.ReadInt();
            int numberOfLevels = bs.ReadInt();

            for (int i = 0; i < numberOfLevels; i++)
            {
                levelByteEnd.Add(new LevelInfo() { PackSize = bs.ReadUInt(), UncompressedSize = bs.ReadUInt() });
            }

            if (streamVersion >= 2)
            {
                completeFileSize = bs.ReadUInt();
            }

            if (streamVersion >= 3)
            {
                dataHeaderSize = bs.ReadUInt();
            }

            bs.ReadByte();
        }
示例#2
0
        public override Task SendMessageAsync(ByteArray message, CancellationToken token)
        {
            if (token.IsCancellationRequested)
                return Task.FromResult<object>(null);

            return udp.SendAsync(message, message.Length);
        }
 public System.Collections.Generic.List<object> GenerateByteArray(byte[] bytes)
 {
     ByteArray data = new ByteArray(bytes);
     System.Collections.Generic.List<object> list = new System.Collections.Generic.List<object>();
     int length = data.ReadInt();
     for (int i = 0; (i < length); i = (i + 1))
     {
         BuildingTemplateVO vo = new BuildingTemplateVO();
         vo.id = data.ReadInt();
         vo.name = data.ReadUTF();
         vo.type = data.ReadInt();
         vo.buildingIndex = data.ReadInt();
         vo.camp = data.ReadInt();
         vo.image = data.ReadUTF();
         vo.levelMap = data.ReadInt();
         vo.affiliation = data.ReadInt();
         vo.openNeedThLevel = data.ReadInt();
         vo.isInitZore = data.ReadInt();
         vo.levelRule = data.ReadInt();
         vo.gold = data.ReadInt();
         vo.wood = data.ReadInt();
         vo.crystal = data.ReadInt();
         vo.stone = data.ReadInt();
         vo.sulfur = data.ReadInt();
         vo.diamond = data.ReadInt();
         vo.upgradeCdTime = data.ReadInt();
         vo.productActorId = data.ReadInt();
         vo.makeCurrencyId = data.ReadInt();
         vo.desc = data.ReadUTF();
         vo.isOpen = data.ReadInt();
         list.Add(vo);
     }
     return list;
 }
 public ImageSheetModel(DeckModel deck, Guid id, SheetDisposition disp, Rectangle bounds, ByteArray md5, int height)
     : base(id, disp, bounds, false, height)
 {
     this.m_MD5 = md5;
     this.m_Deck = deck;
     this.visible_ = true;
 }
示例#5
0
    /// <summary>
    /// 将消息体编码
    /// </summary>
    /// <param name="type"></param>
    /// <param name="area"></param>
    /// <param name="command"></param>
    /// <param name="message"></param>
    public void Write(byte type, int area, int command, object message)
    {
        ByteArray ba = new ByteArray();
        ba.Write(type);
        ba.Write(area);
        ba.Write(command);

        if (message != null)
        {
            ba.Write(SerializeUtil.Encode(message));
        }

        //进行黏包处理
        ByteArray arrl = new ByteArray();
        arrl.Write(ba.Length);
        arrl.Write(ba.GetBuff());
        try
        {
            socket.Send(arrl.GetBuff());
        }
        catch(Exception e)
        {
            Debug.Log("网络错误,请重新登录" + e.Message);
        }
    }
示例#6
0
 public ByteArray(ByteArray src, byte[] data, int pos) {
   if(data==null) {
     return;
   }
   if(src==null) {
     if(pos<0) {
       pos=0;
     }
     _val=new byte[pos+data.Length];
     Buffer.BlockCopy(data, 0, _val, pos, data.Length);
   } else {
     if(pos<0) {  // negative => position from end
       pos=src._val.Length+1+pos;
     }
     if(pos>=src._val.Length) {
       _val=new byte[pos+data.Length];
       Buffer.BlockCopy(src._val, 0, _val, 0, src._val.Length);
       Buffer.BlockCopy(data, 0, _val, pos, data.Length);
     } else if(pos==0) {
       _val=new byte[src._val.Length+data.Length];
       Buffer.BlockCopy(data, 0, _val, 0, data.Length);
       Buffer.BlockCopy(src._val, 0, _val, data.Length, src._val.Length);
     } else {
       _val=new byte[src._val.Length+data.Length];
       Buffer.BlockCopy(src._val, 0, _val, 0, pos);
       Buffer.BlockCopy(data, 0, _val, pos, data.Length);
       Buffer.BlockCopy(src._val, pos, _val, pos+data.Length, src._val.Length-pos);
     }
   }
 }
示例#7
0
		public void upload(ByteArray vertexProgram, ByteArray fragmentProgram) {
			// convert shaders from AGAL to GLSL
			var glslVertex = AGALConverter.ConvertToGLSL(vertexProgram);
			var glslFragment = AGALConverter.ConvertToGLSL(fragmentProgram);
			// upload as GLSL
			uploadFromGLSL(glslVertex, glslFragment);
		}
示例#8
0
        public static bool parseXMLFile()
        {
            ByteArray bytes = ResourcePool.remove(GameConfig.XML_LIB_URL) as ByteArray;
            if (bytes != null) {
                try {
                    bytes.Uncompress();
                } catch (Exception e) {
                }

                map = new Dictionary<string,object>();
                while (bytes.Length != bytes.Postion) {
                    string name = bytes.readUTF();
                    if(name == "fish.xml"){
                        Debug.Log(name);
                    }
                    int size = bytes.readInt();
                    if (size > bytes.Length)
                    {
                        return false;
                    }
                    ByteArray xmlData;
                    byte[] xmlDataList = new byte[size];
                    bytes.readBytes(xmlDataList, 0, (uint)size);
                    xmlData = new ByteArray(xmlDataList);
                    map[name] = xmlData;
                }
                return true;
            }
            return false;
        }
        public void Read(ByteArray inData, AssetHeader assetHeader)
        {
            if (assetHeader.GetVersion() >= 7)
            {
                inData.ReadStringNull();
                attributes = inData.ReadInt();
            }

            int numBaseClasses = inData.ReadInt();
            Debug.Log("numBaseClasses:" + numBaseClasses);
            for (int i = 0; i < numBaseClasses; i++)
            {
                int classID = inData.ReadInt();

                FieldTypeNode node = new FieldTypeNode();
                node.Read(inData);

                typeMap.Add(classID, node);
            }

            // padding
            if (assetHeader.GetVersion() >= 7)
            {
                inData.ReadInt();
            }
        }
示例#10
0
文件: Int.cs 项目: Okalmas/s7netplus
 public static byte[] ToByteArray(Int16[] value)
 {
     ByteArray arr = new ByteArray();
     foreach (Int16 val in value)
         arr.Add(ToByteArray(val));
     return arr.array;
 }
 public ByteArray GenerateByteArray(object data)
 {
     List<BuildingTemplateVO> list = data as List<BuildingTemplateVO>;
     ByteArray ba = new ByteArray();
     int length = list.Count;
     ba.WriteInt(length);
     for (int i = 0; (i < length); i = (i + 1))
     {
         ba.WriteInt(list[i].id);
         ba.WriteUTF(list[i].name);
         ba.WriteInt(list[i].type);
         ba.WriteInt(list[i].buildingIndex);
         ba.WriteInt(list[i].camp);
         ba.WriteUTF(list[i].image);
         ba.WriteInt(list[i].levelMap);
         ba.WriteInt(list[i].affiliation);
         ba.WriteInt(list[i].openNeedThLevel);
         ba.WriteInt(list[i].isInitZore);
         ba.WriteInt(list[i].levelRule);
         ba.WriteInt(list[i].gold);
         ba.WriteInt(list[i].wood);
         ba.WriteInt(list[i].crystal);
         ba.WriteInt(list[i].stone);
         ba.WriteInt(list[i].sulfur);
         ba.WriteInt(list[i].diamond);
         ba.WriteInt(list[i].upgradeCdTime);
         ba.WriteInt(list[i].productActorId);
         ba.WriteInt(list[i].makeCurrencyId);
         ba.WriteUTF(list[i].desc);
         ba.WriteInt(list[i].isOpen);
     }
     return ba;
 }
示例#12
0
 public ByteArray GetBytes()
 {
     if (writeObject == null) throw new Exception("write object is null");
     var byteArray = new ByteArray();
     byteArray.WriteObject(writeObject);
     return byteArray;
 }
示例#13
0
文件: NetProto.cs 项目: en/libunity
        public static auto_id UnPack(ByteArray reader)
        {
            auto_id tbl = new auto_id();
            tbl.id = reader.ReadInt32();

            return tbl;
        }
示例#14
0
 public static void TestByteArrayWrite()
 {
     ByteArray ba = new ByteArray();
     ba.write(5);
     ByteArray ba2 = new ByteArray();
     ba2.write(ba.getBuff());
 }
示例#15
0
		private static uint readUInt24(ByteArray data)
		{
			uint value;
			value  = (data.readUnsignedByte() << 16);
			value |= (data.readUnsignedByte() << 8);
			value |=  data.readUnsignedByte();
			return value;
		}
 public void Read(ByteArray inData)
 {
     name = inData.ReadStringNull();
     offset = inData.ReadUInt();
     size = inData.ReadUInt();
     Debug.Log(string.Format("name={0},offset={1},size={2}",name,offset,size));
     //36+4+4=44
 }
示例#17
0
 private void AppendBytes(ByteArray message, LogEventInfo logEvent, string invalidNamesPattern, EncodingSet encodings)
 {
     AppendNameBytes(message, logEvent, invalidNamesPattern, encodings);
     message.Append(EqualBytes);
     message.Append(QuotesBytes);
     AppendValueBytes(message, logEvent, encodings);
     message.Append(QuotesBytes);
 }
		public static MemoryStream ReadToMemoryStream(this BinaryReader e, int length)
		{
			var o = new ByteArray();

			e.BaseStream.ToByteArray().readBytes(o, 0, (uint)length);

			return o.ToMemoryStream();
		}
示例#19
0
 private void AppendHeaderBytes(ByteArray buffer, LogEventInfo logEvent, Encoding encoding)
 {
     var timestamp = string.Format(CultureInfo.InvariantCulture, TimestampFormat, logEvent.TimeStamp);
     var host = hostnamePolicySet.Apply(hostnameLayout.Render(logEvent));
     var header = $"{timestamp} {host}";
     var headerBytes = encoding.GetBytes(header);
     buffer.Append(headerBytes);
 }
示例#20
0
文件: NetProto.cs 项目: en/libunity
        public static error_info UnPack(ByteArray reader)
        {
            error_info tbl = new error_info();
            tbl.code = reader.ReadInt32();
            tbl.msg = reader.ReadUTFBytes();

            return tbl;
        }
示例#21
0
        public override ByteArray Write()
        {
            ByteArray data = new ByteArray();

            data.WriteInt32(texture);

            return data;
        }
		static MandelbrotProxy()
		{
			var __loader = new cmodule.Mandelbrot.CLibInit();
			var __lib = new DynamicDelegatesContainer { Subject = __loader.init() };
			MandelbrotProxy.Memory = get_ds(new Namespace("cmodule.Mandelbrot"));
			MandelbrotProxy.InitializeMandelbrotProvider = __lib.ToFunc<int>("InitializeMandelbrotProvider");
			MandelbrotProxy.DrawMandelbrotSet = __lib.ToFunc<int, uint>("DrawMandelbrotSet");
		}
 public LogEventMsgSet(AsyncLogEventInfo asyncLogEvent, ByteArray buffer, MessageBuilder messageBuilder, MessageTransmitter messageTransmitter)
 {
     this.asyncLogEvent = asyncLogEvent;
     this.buffer = buffer;
     this.messageBuilder = messageBuilder;
     this.messageTransmitter = messageTransmitter;
     currentMessage = 0;
 }
        public Block GenerateBlock(
            ByteArray blockHash,
            ByteArray transactionHash,
            InputInfo[] inputs,
            OutputInfo[] outputs)
        {
            BlockHeader blockHeader = new BlockHeader()
            {
                BlockHash = blockHash,
                BlockNonce = 0,
                BlockTargetDifficulty = 0,
                BlockTimestamp = this.GetCurrentBlockTimeStamp(),
                BlockTimestampUnix = 0,
                BlockVersion = 1,
                MerkleRootHash = ByteArray.Empty,
                PreviousBlockHash = this.previousBlockHash,
            };

            this.blockTimeStamp = this.blockTimeStamp.AddDays(1);

            string expectedFileName = string.Format(CultureInfo.InvariantCulture, "blk{0:00000}.dat", this.GetCurentBlockchainFileIndex());
            Block block = new Block(expectedFileName, blockHeader);

            Transaction transaction = new Transaction()
            {
                TransactionHash = transactionHash,
                TransactionLockTime = 0,
                TransactionVersion = 1,
            };

            foreach (InputInfo inputInfo in inputs)
            {
                TransactionInput transactionInput = new TransactionInput()
                {
                    InputScript = ByteArray.Empty,
                    SourceTransactionHash = inputInfo.SourceTransactionHash,
                    SourceTransactionOutputIndex = inputInfo.SourceTransactionOutputIndex,
                };
                transaction.AddInput(transactionInput);
            }

            foreach (OutputInfo outputInfo in outputs)
            {
                TransactionOutput transactionOutput = new TransactionOutput()
                {
                    OutputScript = ByteArray.Empty,
                    OutputValueSatoshi = (ulong)(outputInfo.OutputValueSatoshi * DatabaseGenerator.BtcToSatoshi),
                };

                transaction.AddOutput(transactionOutput);
            }

            block.AddTransaction(transaction);

            this.previousBlockHash = block.BlockHeader.BlockHash;

            return block;
        }
        public virtual byte[] ReadBytes(int length)
        {
            var k = new ByteArray();
            var s = InternalStream.ToByteArray();

            s.readBytes(k, 0, (uint)length);

            return k.ToArray();
        }
示例#26
0
 public Block(long blockId, int blockchainFileId, int blockVersion, ByteArray blockHash, ByteArray previousBlockHash, DateTime blockTimestamp)
 {
     this.BlockId = blockId;
     this.BlockchainFileId = blockchainFileId;
     this.BlockVersion = blockVersion;
     this.BlockHash = blockHash;
     this.PreviousBlockHash = previousBlockHash;
     this.BlockTimestamp = blockTimestamp;
 }
示例#27
0
        override public void parseByteArrayTestServer(ByteArray bytes)
        {
            base.parseByteArrayTestServer(bytes);

            // 读取内容
            m_field2 = bytes.readUnsignedLong();
            m_field3 = bytes.readFloat();
            // 服务器读取字符串方法
            m_field4 = bytes.readMultiByte(256, GkEncode.UTF8);
        }
示例#28
0
 internal static ByteArray FromSave(GameSave gameSave, Tuple<int, uint> address)
 {
     ByteArray byteArray;
     if (!gameSave.TryGetFromBlockStructureCache(address, out byteArray))
     {
         byteArray = new ByteArray(gameSave, address);
         gameSave.AddToBlockStructureCache(address, byteArray);
     }
     return byteArray;
 }
        public void Read(ByteArray inData)
        {
            offset = inData.ReadUInt();
            length = inData.ReadUInt();
            typeID = inData.ReadInt();
            classID = inData.ReadShort();
            isDestroyed = inData.ReadShort();

            Debug.Log(string.Format("offset={0},length={1},typeID={2},classID={3},isDestroyed={4}", offset, length, typeID, classID, isDestroyed));
        }
示例#30
0
		public void WriteData(AMFWriter writer, object data)
		{
			if(data is byte[])
				data = new ByteArray(data as byte[]);

			if(data is ByteArray)
			{
				writer.WriteByteArray(data as ByteArray);
			}
		}
示例#31
0
        private void Read()
        {
            int msglength  = 0;
            int msgNameLen = 0;

            while (true)
            {
                try
                {
                    if (this.State != TCPSocketLayer.States.Connected)
                    {
                        UnityEngine.Debug.Log("Recive Thread DisConnect-->");
                        break;
                    }

                    if (this.socketPollSleep > 0)
                    {
                        TCPSocketLayer.Sleep(this.socketPollSleep);
                    }
                    if (this.connection.Client.Poll(-1, SelectMode.SelectRead) || this.connection.Client.Poll(-1, SelectMode.SelectError))
                    {
                        byte[] headerBytes = new byte[9];
                        int    i           = this.connection.Client.Receive(headerBytes);
                        if (i <= 0)
                        {
                            this.Disconnect();
                            break;
                        }

                        ProtoBufPackageHeader header = new ProtoBufPackageHeader();
                        int iHeaderLen = header.ReturnHeaderLen();
                        header.ReadFrom(headerBytes, 0);
                        msglength  = header.MessageLength - iHeaderLen;
                        msgNameLen = header.MessageTypeLength;
                        if (0 == msglength)
                        {
                            ResponsePing();
                            continue;
                        }
                    }
                    if (this.connection.Client.Poll(-1, SelectMode.SelectRead) || this.connection.Client.Poll(-1, SelectMode.SelectError))
                    {
                        byte[] msgbytes = new byte[msglength];
                        int    i        = this.connection.Client.Receive(msgbytes);
                        if (i <= 0)
                        {
                            this.Disconnect();
                            break;
                        }
                        ByteArray byteArray = new ByteArray();
                        byteArray.WriteBytes(msgbytes);
                        UnityEngine.Debug.Log("TCP Socket 收到的字节:  " + DefaultObjectDumpFormatter.HexDump(byteArray));
                        this.HandleBinaryProtoBufData(byteArray.Bytes, byteArray.Bytes.Length, msgNameLen);
                    }
                }
                catch (Exception ex)
                {
                    this.HandleError("General error reading data from socket: " + ex.Message + " " + ex.StackTrace);
                    break;
                }
            }
        }
示例#32
0
 public bool Load(string path, V[] values) => Load(ByteArray.Create(path), values);
示例#33
0
 public override void read(ByteArray byteArray)
 {
     name = byteArray.Readstring();
     x    = byteArray.ReadInt32();
     y    = byteArray.ReadInt32();
 }
示例#34
0
 public override void write(ByteArray byteArray)
 {
     byteArray.Writestring(name);
     byteArray.WriteInt32(x);
     byteArray.WriteInt32(y);
 }
示例#35
0
        // this class was generated by alchemy and
        // may be represented by 2664.achacks.as

        public void supplyFile(string path, ByteArray data)
        {
        }
示例#36
0
 public override void Decode(ByteArray array)
 {
     array.ReadByte();
     MaximumData = array.ReadVariableInteger();
 }
示例#37
0
 private static long GetRelationshipId(ByteArray array, long nodeId)
 {
     return(array.Get6ByteLong(nodeId, SPARSE_ID_OFFSET));
 }
示例#38
0
 public void uploadFromByteArray(ByteArray data, int byteArrayOffset, int startOffset, int count)
 {
     throw new NotImplementedException();
 }
示例#39
0
        // 获得资源。包装版本 -- 返回本地映射文件、Cache版本。
        // return:
        //		-1	出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。
        //		0	成功
        public static long GetResLocalFile(this LibraryChannel channel,
                                           DigitalPlatform.Stop stop,
                                           CfgCache cache,
                                           string strPath,
                                           string strStyle,
                                           out string strOutputFilename,
                                           out string strMetaData,
                                           out byte[] baOutputTimeStamp,
                                           out string strOutputResPath,
                                           out string strError)
        {
            strOutputFilename = "";

            byte[] cached_timestamp = null;
            string strTimeStamp;
            string strLocalName;
            string strResult = "";

            string strFullPath = channel.Url + "?" + strPath;

            if (StringUtil.IsInList("forceget", strStyle) == true)
            {
                // 强制获取
                StringUtil.RemoveFromInList("forceget",
                                            true,
                                            ref strStyle);
                goto GETDATA;
            }

            // 从cache中得到timestamp
            // return:
            //      -1  error
            //		0	not found
            //		1	found
            int nRet = cache.FindLocalFile(strFullPath,
                                           out strLocalName,
                                           out strTimeStamp);

            if (nRet == -1)
            {
                strOutputResPath  = "";
                strMetaData       = "";
                baOutputTimeStamp = null;
                strError          = "CfgCache 尚未初始化";
                return(-1);
            }
            if (nRet == 1)
            {
                Debug.Assert(strLocalName != "", "FindLocalFile()返回的strLocalName为空");

                if (strTimeStamp == "")
                {
                    goto GETDATA;   // 时间戳不对, 那就只好重新获取服务器端内容
                }
                Debug.Assert(strTimeStamp != "", "FindLocalFile()获得的strTimeStamp为空");
                cached_timestamp = ByteArray.GetTimeStampByteArray(strTimeStamp);
                // bExistInCache = true;
            }
            else
            {
                goto GETDATA;
            }

            // 探测时间戳关系
            string strNewStyle = strStyle;

            /*
             * StringUtil.RemoveFromInList("data",
             *  true,
             *  ref strNewStyle);	// 不要数据体
             * */
            StringUtil.RemoveFromInList("content,data,metadata", // 2012/12/31 BUG 以前忘记了加入content
                                        true,
                                        ref strNewStyle);        // 不要数据体和metadata

            long lRet = channel.GetRes(stop,
                                       strPath,
                                       strNewStyle,
                                       out strResult,
                                       out strMetaData,
                                       out baOutputTimeStamp,
                                       out strOutputResPath,
                                       out strError);

            if (lRet == -1)
            {
                return(-1);
            }

            // 如果证明timestamp没有变化, 但是本次并未返回内容,则从cache中取原来的内容

            if (ByteArray.Compare(baOutputTimeStamp, cached_timestamp) == 0)    // 时间戳相等
            {
                Debug.Assert(strLocalName != "", "strLocalName不应为空");

                strOutputFilename = strLocalName;
                // TODO: 这里返回 0 似乎不严谨。但是否应该返回 byte[] 的 Length 呢?
                return(0);   // 以无错误姿态返回
            }

GETDATA:
            // 重新正式获取内容
            lRet = channel.GetRes(
                stop,
                strPath,
                strStyle,
                out strResult,
                out strMetaData,
                out baOutputTimeStamp,
                out strOutputResPath,
                out strError);
            if (lRet == -1)
            {
                return(-1);
            }

            // 因为时间戳不匹配而新获得了内容
            // 保存到cache
            cache.PrepareLocalFile(strFullPath, out strLocalName);
            Debug.Assert(strLocalName != "", "PrepareLocalFile()返回的strLocalName为空");

            // 写入文件,以便以后从cache获取
            using (StreamWriter sw = new StreamWriter(strLocalName,
                                                      false, // append
                                                      System.Text.Encoding.UTF8))
            {
                sw.Write(strResult);
            }

            Debug.Assert(baOutputTimeStamp != null, "下层GetRes()返回的baOutputTimeStamp为空");
            nRet = cache.SetTimeStamp(strFullPath,
                                      ByteArray.GetHexTimeStampString(baOutputTimeStamp),
                                      out strError);
            if (nRet == -1)
            {
                return(-1);
            }

            strOutputFilename = strLocalName;
            return(lRet);
        }
示例#40
0
        // 上传文件到到 dp2lbrary 服务器
        // 注:已通过 prompt_func 实现通讯出错时候重试
        // parameters:
        //      timestamp   时间戳。如果为 null,函数会自动根据文件信息得到一个时间戳
        //      bRetryOverwiteExisting   是否自动在时间戳不一致的情况下覆盖已经存在的服务器文件。== true,表示当发现时间戳不一致的时候,自动用返回的时间戳重试覆盖
        // return:
        //		-1	出错
        //		0   上传文件成功
        public static int UploadFile(
            this LibraryChannel channel,
            Stop stop,
            string strClientFilePath,
            string strServerFilePath,
            string strMetadata,
            string strStyle,
            byte[] timestamp,
            bool bRetryOverwiteExisting,
            bool bProgressChange,
            delegate_prompt prompt_func,
            out byte[] output_timestamp,
            out string strError)
        {
            strError         = "";
            output_timestamp = null;

            string strResPath = strServerFilePath;

#if NO
            if (string.IsNullOrEmpty(strMime))
            {
                strMime = PathUtil.MimeTypeFrom(strClientFilePath);
            }
#endif

            // 只修改 metadata
            if (string.IsNullOrEmpty(strClientFilePath) == true)
            {
                long lRet = channel.SaveResObject(
                    stop,
                    strResPath,
                    null, // strClientFilePath,
                    -1,   // 0, // 0 是 bug,会导致清除原有对象内容 2018/8/13
                    strMetadata,
                    "",
                    timestamp,
                    strStyle,
                    out output_timestamp,
                    out strError);
                timestamp = output_timestamp;
                if (lRet == -1)
                {
                    return(-1);
                }
                return(0);
            }

            long skip_offset = 0;

            {
REDO_DETECT:
                // 先检查以前是否有已经上传的局部
                long lRet = channel.GetRes(stop,
                                           strServerFilePath,
                                           0,
                                           0,
                                           "uploadedPartial",
                                           out byte[] temp_content,
                                           out string temp_metadata,
                                           out string temp_outputPath,
                                           out byte[] temp_timestamp,
                                           out strError);
                if (lRet == -1)
                {
                    if (channel.ErrorCode == LibraryClient.localhost.ErrorCode.NotFound)
                    {
                        // 以前上传的局部不存在,说明只能从头上传
                        skip_offset = 0;
                    }
                    else
                    {
                        // 探测过程通讯或其他出错
                        if (prompt_func != null)
                        {
                            if (stop != null && stop.State != 0)
                            {
                                strError = "用户中断";
                                return(-1);
                            }

                            string action = prompt_func(channel,
                                                        strError + "\r\n\r\n(重试) 重试操作; (中断) 中断处理",
                                                        new string[] { "重试", "中断" },
                                                        10);
                            if (action == "重试")
                            {
                                goto REDO_DETECT;
                            }
                            if (action == "中断")
                            {
                                return(-1);
                            }
                        }
                        return(-1);
                    }
                }
                else if (lRet > 0)
                {
                    // *** 发现以前存在 lRet 这么长的已经上传部分
                    long local_file_length = FileUtil.GetFileLength(strClientFilePath);
                    // 本地文件尺寸居然小于已经上传的临时部分
                    if (local_file_length < lRet)
                    {
                        // 只能从头上传
                        skip_offset = 0;
                    }
                    else
                    {
                        // 询问是否断点续传
                        if (prompt_func != null)
                        {
                            string percent = StringUtil.GetPercentText(lRet, local_file_length);
                            string action  = prompt_func(null,
                                                         $"本地文件 {strClientFilePath} 以前曾经上传过长度为 {lRet} 的部分内容(占整个文件 {percent}),请问现在是否继续上传余下部分? \r\n[是]从断点位置开始继续上传; [否]从头开始上传; [中断]取消这个文件的上传",
                                                         new string[] { "是", "否", "中断" },
                                                         0);
                            if (action == "是")
                            {
                                skip_offset = lRet;
                            }
                            else if (action == "否")
                            {
                                skip_offset = 0;
                            }
                            else
                            {
                                strError = "取消处理";
                                return(-1);
                            }
                        }
                        // 如果 prompt_func 为 null 那就不做断点续传,效果是从头开始上传
                    }
                }
            }

            // 检测文件尺寸
            FileInfo fi = new FileInfo(strClientFilePath);
            if (fi.Exists == false)
            {
                strError = "文件 '" + strClientFilePath + "' 不存在...";
                return(-1);
            }

            string[] ranges = null;

            if (fi.Length == 0)
            {
                // 空文件
                ranges    = new string[1];
                ranges[0] = "";
            }
            else
            {
                string strRange = "";
                strRange = $"{skip_offset}-{(fi.Length - 1)}";

                // 按照100K作为一个chunk
                // TODO: 实现滑动窗口,根据速率来决定chunk尺寸
                ranges = RangeList.ChunkRange(strRange,
                                              channel.UploadResChunkSize // 500 * 1024
                                              );
                if (bProgressChange && stop != null)
                {
                    stop.SetProgressRange(0, fi.Length);
                }
            }

            if (timestamp == null)
            {
                timestamp = FileUtil.GetFileTimestamp(strClientFilePath);
            }

            // byte[] output_timestamp = null;

            string strWarning = "";

            TimeSpan old_timeout = channel.Timeout;
            try
            {
                using (FileStream stream = File.OpenRead(strClientFilePath))
                {
                    for (int j = 0; j < ranges.Length; j++)
                    {
                        if (stop != null && stop.State != 0)
                        {
                            strError = "用户中断";
                            return(-1);
                        }

                        string range = ranges[j];

                        string strWaiting = "";
                        if (j == ranges.Length - 1)
                        {
                            strWaiting      = " 请耐心等待...";
                            channel.Timeout = new TimeSpan(0, 40, 0);   // 40 分钟
                        }

                        string    strPercent = "";
                        RangeList rl         = new RangeList(range);
                        if (rl.Count != 1)
                        {
                            strError = $"{range} 中只应包含一个连续范围";
                            return(-1);
                        }

                        {
                            double ratio = (double)((RangeItem)rl[0]).lStart / (double)fi.Length;
                            strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%";
                        }

                        if (stop != null)
                        {
                            stop.SetMessage( // strMessagePrefix +
                                "正在上载 " + range + "/"
                                + StringUtil.GetLengthText(fi.Length)
                                + " " + strPercent + " " + strClientFilePath + strWarning + strWaiting);
                            if (bProgressChange && rl.Count > 0)
                            {
                                stop.SetProgressValue(rl[0].lStart);
                            }
                        }

                        // 2019/6/23
                        StreamUtil.FastSeek(stream, rl[0].lStart);

                        int  nRedoCount = 0;
                        long save_pos   = stream.Position;
REDO:
                        // 2019/6/21
                        // 如果是重做,文件指针要回到合适位置
                        if (stream.Position != save_pos)
                        {
                            StreamUtil.FastSeek(stream, save_pos);
                        }

                        long lRet = channel.SaveResObject(
                            stop,
                            strResPath,
                            stream,                                      // strClientFilePath,
                            -1,
                            j == ranges.Length - 1 ? strMetadata : null, // 最尾一次操作才写入 metadata
                            range,
                            // j == ranges.Length - 1 ? true : false,	// 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间
                            timestamp,
                            strStyle,
                            out output_timestamp,
                            out strError);
                        if (channel.ErrorCode == DigitalPlatform.LibraryClient.localhost.ErrorCode.TimestampMismatch)
                        {
                            strError = $"{strError}。timestamp={ByteArray.GetHexTimeStampString(timestamp)},output_timestamp={ByteArray.GetHexTimeStampString(output_timestamp)}。parsed:{ParseTimestamp(timestamp)};{ParseTimestamp(output_timestamp)}";
                        }

                        // Debug.WriteLine($"parsed:{ParseTimestamp(timestamp)};{ParseTimestamp(output_timestamp)}");

                        timestamp = output_timestamp;

                        strWarning = "";

                        if (lRet == -1)
                        {
                            // 如果是第一个 chunk,自动用返回的时间戳重试一次覆盖
                            if (bRetryOverwiteExisting == true &&
                                j == 0 &&
                                channel.ErrorCode == DigitalPlatform.LibraryClient.localhost.ErrorCode.TimestampMismatch &&
                                nRedoCount == 0)
                            {
                                nRedoCount++;
                                goto REDO;
                            }

                            if (prompt_func != null)
                            {
                                if (stop != null && stop.State != 0)
                                {
                                    strError = "用户中断";
                                    return(-1);
                                }

                                string action = prompt_func(channel,
                                                            strError + "\r\n\r\n(重试) 重试操作; (中断) 中断处理",
                                                            new string[] { "重试", "中断" },
                                                            10);
                                if (action == "重试")
                                {
                                    goto REDO;
                                }
                                if (action == "中断")
                                {
                                    return(-1);
                                }
                            }
                            return(-1);
                        }
                    }
                }

                if (StringUtil.IsInList("_checkMD5", strStyle))
                {
                    stop?.SetMessage($"正在校验本地文件 {strClientFilePath} 和刚上传的服务器文件 {strServerFilePath} ...");
                    // result.Value:
                    //      -1  出错
                    //      0   不匹配
                    //      1   匹配
                    // exception:
                    //      可能会抛出异常
                    var result = CheckMD5(
                        channel,
                        stop,
                        strServerFilePath,
                        strClientFilePath);

                    stop?.SetMessage("MD5 校验完成");

                    if (result.Value == -1)
                    {
                        strError = result.ErrorInfo;
                        return(-1);
                    }
                    if (result.Value == 0)
                    {
                        strError = $"UploadFile() 出错:本地文件 {strClientFilePath} 和刚上传的服务器文件 {strServerFilePath} MD5 校验不一致。请重新上传";
                        return(-1);
                    }
                    Debug.Assert(result.Value == 1, "");
                }
            }
            catch (Exception ex)
            {
                strError = "UploadFile() 出现异常: " + ExceptionUtil.GetDebugText(ex);
                return(-1);
            }
            finally
            {
                channel.Timeout = old_timeout;
            }

            return(0);
        }
示例#41
0
 public abstract void Decode(ByteArray array);
示例#42
0
 internal virtual void ClearRelationshipIds(ByteArray array, long index)
 {
     array.Set6ByteLong(index, IdOffset(Direction.OUTGOING), EMPTY);
     array.Set6ByteLong(index, IdOffset(Direction.INCOMING), EMPTY);
     array.Set6ByteLong(index, IdOffset(Direction.BOTH), EMPTY);
 }
示例#43
0
 internal virtual int GetTypeId(ByteArray array, long index)
 {
     return(unsignedShortToInt(array.GetShort(index, TYPE_OFFSET)));
 }
示例#44
0
 private static long All48Bits(ByteArray array, long index, int offset)
 {
     return(All48Bits(array.Get6ByteLong(index, offset)));
 }
示例#45
0
 internal BlockPair(ByteArray data, ByteArray errorCorrection)
 {
     dataBytes            = data;
     errorCorrectionBytes = errorCorrection;
 }
示例#46
0
        public SngServer()
        {
            m_runLoop = true;

            m_netServer.AttachProxy(m_S2CProxy);
            m_netServer.AttachStub(m_C2SStub);

            m_netServer.ConnectionRequestHandler = (AddrPort clientAddr, ByteArray userDataFromClient, ByteArray reply) =>
            {
                reply = new ByteArray();
                reply.Clear();
                return(true);
            };

            m_netServer.ClientHackSuspectedHandler = (HostID clientID, HackType hackType) =>
            {
            };

            m_netServer.ClientJoinHandler = (NetClientInfo clientInfo) =>
            {
                Console.WriteLine("OnClientJoin: {0} ", clientInfo.hostID);
            };

            m_netServer.ClientLeaveHandler = (NetClientInfo clientInfo, ErrorInfo errorInfo, ByteArray comment) =>
            {
                Console.WriteLine("OnClientLeave: {0}", clientInfo.hostID);

                Monitor.Enter(this);
                Ville_S ville;

                //remove the client and play info, and then remove the ville if it is empty.
                if (m_remoteClients.TryGetValue(clientInfo.hostID, out ville))
                {
                    RemoteClient_S clientValue;
                    Ville_S        villeValue;
                    bool           changeMaster;
                    int            changedMasterValue;

                    ville.m_players.TryRemove(clientInfo.hostID, out clientValue);
                    m_remoteClients.TryRemove(clientInfo.hostID, out villeValue);

                    //방장 바꾸기, 칸바꾸기
                    ville.UpdateNextLoc(clientValue.waitingIdx);

                    changeMaster       = false;
                    changedMasterValue = -1;

                    if (clientInfo.hostID == ville.masterID && ville.m_players != null)        // master leaved
                    {
                        changeMaster = true;
                        if (ville.m_players.Count != 0)
                        {
                            ville.masterID = ville.m_players.Keys.First();
                        }
                        changedMasterValue = (int)ville.masterID;
                        Console.WriteLine("masterID changed: {0}->{1}", clientInfo.hostID, changedMasterValue);
                    }

                    if (ville.m_players.Count == 0)
                    {
                        UnloadVille(ville);
                    }
                    else
                    {
                        // notify to all player
                        foreach (KeyValuePair <HostID, RemoteClient_S> iPlayer in ville.m_players)
                        {
                            m_S2CProxy.NotifyPlayerLeave(iPlayer.Key, RmiContext.ReliableSend, (int)ville.m_p2pGroupID, clientValue.waitingIdx, changeMaster, changedMasterValue);
                        }
                    }
                }
                Monitor.Exit(this);
            };

            m_netServer.ErrorHandler = (ErrorInfo errorInfo) =>
            {
                Console.WriteLine("OnError: {0}", errorInfo.ToString());
            };

            m_netServer.WarningHandler = (ErrorInfo errorInfo) =>
            {
                Console.WriteLine("OnWarning! {0}", errorInfo.ToString());
            };

            m_netServer.ExceptionHandler = (Exception e) =>
            {
                Console.WriteLine("OnWarning! {0}", e.Message.ToString());
            };

            m_netServer.InformationHandler = (ErrorInfo errorInfo) =>
            {
                Console.WriteLine("OnInformation! {0}", errorInfo.ToString());
            };

            m_netServer.NoRmiProcessedHandler = (RmiID rmiID) =>
            {
                Console.WriteLine("OnNoRmiProcessed! {0}", rmiID);
            };

            m_netServer.P2PGroupJoinMemberAckCompleteHandler = (HostID groupHostID, HostID memberHostID, ErrorType result) =>
            {
            };

            m_netServer.TickHandler = (Object context) =>
            {
            };

            m_netServer.UserWorkerThreadBeginHandler = () =>
            {
            };

            m_netServer.UserWorkerThreadEndHandler = () =>
            {
            };
            m_C2SStub.RequestLogon = (Nettention.Proud.HostID remote, Nettention.Proud.RmiContext rmiContext, String villeName, String nickName, bool isNewVille) =>
            {
                Monitor.Enter(this);
                Ville_S  ville;
                HostID[] list = m_netServer.GetClientHostIDs();

                if (!m_villes.TryGetValue(villeName, out ville))
                {
                    // create new one
                    ville = new Ville_S();
                    ville.m_p2pGroupID = m_netServer.CreateP2PGroup(list, new ByteArray());
                    ville.masterID     = remote;

                    Console.WriteLine("m_p2pGroupID : {0}", ville.m_p2pGroupID);

                    NetClientInfo info = m_netServer.GetClientInfo(list.Last());
                    Console.WriteLine("Client HostID : {0}, IP:Port : {1}:{2}", info.hostID, info.tcpAddrFromServer.IPToString(), info.tcpAddrFromServer.port);

                    // load ville info
                    m_villes.TryAdd(villeName, ville);
                    ville.m_name = villeName;
                }

                m_villes.TryGetValue(villeName, out ville);
                if (ville.canJoin == false)
                {
                    // can't join
                    m_S2CProxy.ReplyLogon(remote, RmiContext.ReliableSend, (int)ville.m_p2pGroupID, 1, "빈자리가 없습니다.", false);
                }
                else
                {
                    m_S2CProxy.ReplyLogon(remote, RmiContext.ReliableSend, (int)ville.m_p2pGroupID, 0, "", (remote == ville.masterID));
                    MoveRemoteClientToLoadedVille(remote, ville, nickName);
                }

                Monitor.Exit(this);
                return(true);
            };

            m_C2SStub.RequestAddTree = (Nettention.Proud.HostID remote, Nettention.Proud.RmiContext rmiContext, UnityEngine.Vector3 position) =>
            {
                Monitor.Enter(this);

                Ville_S       ville;
                HostID[]      list = m_netServer.GetClientHostIDs();
                WorldObject_S tree = new WorldObject_S();

                if (m_remoteClients.TryGetValue(remote, out ville))
                {
                    // add the tree
                    tree.m_position = position;
                    tree.m_id       = ville.m_nextNewID;
                    ville.m_worldOjbects.TryAdd(tree.m_id, tree);
                    ville.m_nextNewID++;
                }
                else
                {
                    ville = new Ville_S();
                }


                foreach (HostID id in list)
                {
                    // notify the tree's creation to users
                    m_S2CProxy.NotifyAddTree(id, RmiContext.ReliableSend, (int)ville.m_p2pGroupID, tree.m_id, tree.m_position);
                }
                Monitor.Exit(this);
                return(true);
            };

            m_C2SStub.RequestRemoveTree = (Nettention.Proud.HostID remote, Nettention.Proud.RmiContext rmiContext, int treeID) =>
            {
                Monitor.Enter(this);

                // find the ville
                Ville_S ville;
                if (m_remoteClients.TryGetValue(remote, out ville))
                {
                    // find the tree
                    WorldObject_S tree;
                    if (ville.m_worldOjbects.TryGetValue(treeID, out tree))
                    {
                        WorldObject_S obj;
                        ville.m_worldOjbects.TryRemove(treeID, out obj);

                        HostID[] list = m_netServer.GetClientHostIDs();
                        foreach (HostID id in list)
                        {
                            m_S2CProxy.NotifyRemoveTree(id, RmiContext.ReliableSend, (int)ville.m_p2pGroupID, tree.m_id);
                        }
                    }
                }
                Monitor.Exit(this);
                return(true);
            };

            m_C2SStub.RequestEnterGame = (Nettention.Proud.HostID remote, Nettention.Proud.RmiContext rmiContext) =>
            {
                Monitor.Enter(this);
                Ville_S ville;

                if (m_remoteClients.TryGetValue(remote, out ville))
                {
                    if (remote == ville.masterID)
                    {
                        Console.WriteLine("Master request to enter game scene");

                        HostID[] list = m_netServer.GetClientHostIDs();
                        foreach (HostID id in list)
                        {
                            m_S2CProxy.ReplyEnterGame(id, RmiContext.ReliableSend, (int)ville.m_p2pGroupID, true, 0);
                        }
                    }
                    else
                    {
                        Console.WriteLine("who not master request to enter game scene");
                        HostID[] list = m_netServer.GetClientHostIDs();
                        foreach (HostID id in list)
                        {
                            m_S2CProxy.ReplyEnterGame(id, RmiContext.ReliableSend, (int)ville.m_p2pGroupID, false, (int)ville.masterID);
                        }
                    }
                }
                Monitor.Exit(this);
                return(true);
            };
        }
示例#47
0
 private static void SetRelationshipId(ByteArray array, long nodeId, long firstRelId)
 {
     array.Set6ByteLong(nodeId, SPARSE_ID_OFFSET, firstRelId);
 }
示例#48
0
        private void ReadNextBuffer()
        {
            long bytesBeforeTime = BytesBeforeEndOfFrame;
            long frames          = AudioUnitsPerPES;

            bytesBeforeTime += frames * FrameSize;

            StreamBufferEvent ev = new StreamBufferEvent(0 - (FrameSize + 14), InitialPTS + (audioSample * TimePerFrame));

            streamBuffer.AddEvent(ev);
            audioSample++;
            for (int currentFrame = 1; currentFrame < frames; currentFrame++)
            {
                ev = new StreamBufferEvent(0 - FrameSize, InitialPTS + (audioSample * TimePerFrame));
                audioSample++;
                streamBuffer.AddEvent(ev);
            }

            // Attempt to compensate for stream ending
            if (bytesBeforeTime > reader.Remaining)
            {
                bytesBeforeTime = reader.Remaining;
            }

            long packets        = 1 + ((bytesBeforeTime - PACKET_PAYLOAD_LENGTH_PES) / PACKET_PAYLOAD_LENGTH);
            long bytesToConsume = PACKET_PAYLOAD_LENGTH_PES + (packets - 1) * PACKET_PAYLOAD_LENGTH;

            BytesBeforeEndOfFrame = bytesBeforeTime - bytesToConsume;
            if (bytesBeforeTime == reader.Remaining)
            {
                BytesBeforeEndOfFrame = 0;
            }

            int padding = 0;

            if (bytesToConsume > bytesBeforeTime)
            {
                padding        = (int)(bytesToConsume - bytesBeforeTime);
                bytesToConsume = bytesBeforeTime;
            }

            long decoderStamp = (NextTimeStamp * 300);

            for (int i = 0; i < packets; i++)
            {
                ByteArray transportData = new ByteArray();
                transportData.MaxSize = 188;

                //------------------------------
                // Transport Packet Header
                //------------------------------
                // sync_byte = 0x47					(8 bits)
                transportData.Append((byte)0x47);
                transportData.EnterBitMode();
                // transport_error_indicator		(1 bit)
                transportData.AppendBit(0);
                // payload_unit_start_indicator		(1 bit)
                transportData.AppendBit((byte)((i == 0) ? 1 : 0));
                // transport_priority				(1 bit)
                transportData.AppendBit(0);
                // PID								(13 bits)
                transportData.AppendBits(PID, 12, 0);
                // transport_scrambling_code		(2 bits)
                transportData.AppendBits((byte)0x0, 1, 0);
                // adaptation_field_control			(2 bits)
                transportData.AppendBits((byte)((padding > 0) ? 0x3 : 0x1), 1, 0);
                // continuity_counter				(4 bits)
                transportData.AppendBits(ContinuityCounter, 3, 0);
                ContinuityCounter++;
                transportData.LeaveBitMode();

                int used = 4;

                if (padding > 0)
                {
                    transportData.Append((byte)(padding - 1));
                    if (padding > 1)
                    {
                        transportData.Append((byte)0x00);
                    }
                    for (int paddingIndex = 2; paddingIndex < padding; paddingIndex++)
                    {
                        transportData.Append((byte)0xff);
                    }
                    used   += (int)padding;
                    padding = 0;
                }

                if (i == 0)
                {
                    //-------------------------------
                    // PES Packet Header
                    //-------------------------------
                    // packet_start_code_prefix			(24 bits)	(24)
                    // streaid						(8 bits)	(32)
                    transportData.Append((uint)0x000001BD);
                    long packetLengthPosition = transportData.length;

                    ushort packetLength = (ushort)(bytesToConsume + 8);
                    // Fill with dummy value
                    transportData.Append(packetLength);

                    // '10'								(2 bits)	(02)	0x8000
                    // PES_scrambling_code				(2 bits)	(04)	0x0000
                    // PES_priority						(1 bit)		(05)	0x0000
                    // data_alignment_indicator			(1 bit)		(06)	0x0400
                    // copyright						(1 bit)		(07)	0x0000
                    // original_or_copy					(1 bit)		(08)	0x0000
                    // PTS_DTS_flags = '10'				(2 bits)	(10)	0x0080
                    // ESCR_flag						(1 bit)		(11)	0x0000
                    // ES_rate_flag						(1 bit)		(12)	0x0000
                    // DStrick_mode_flag				(1 bit)		(13)	0x0000
                    // additional_copy_info				(1 bit)		(14)	0x0000
                    // PES_CRC_flag						(1 bit)		(15)	0x0000
                    // PES_extension_flag				(1 bit)		(16)	0x0000
                    //														0x8480
                    transportData.Append((ushort)0x8480);

                    // PES_header_data_length = 0x05	(8 bits)	(08)
                    transportData.Append((byte)0x05);

                    //   '0010'							(4 bits)	(76)
                    //   PTS[32..30]					(3 bits)	(79)
                    //   marker_bit						(1 bit)		(80)
                    //   PTS[29..15]					(15 bits)	(95)
                    //   marker_bit						(1 bit)		(96)
                    //   PTS[14..0]						(15 bits)	(111)
                    //   marker_bit						(1 bit)		(112)
                    transportData.EnterBitMode();
                    transportData.AppendBits((byte)0x2, 3, 0);
                    transportData.AppendBits(NextTimeStamp, 32, 30);
                    transportData.AppendBit(1);
                    transportData.AppendBits(NextTimeStamp, 29, 15);
                    transportData.AppendBit(1);
                    transportData.AppendBits(NextTimeStamp, 14, 0);
                    transportData.AppendBit(1);
                    transportData.LeaveBitMode();

                    NextTimeStamp += AudioUnitDuration90Khz * frames;
                    used          += 14;
                }

                int  payloadLength           = PACKET_LENGTH - used;
                long payloadTransmissionTime = (long)27000000 * (long)payloadLength / (((long)BitRate * 1000) / 8);

                for (int k = 0; k < payloadLength; k++)
                {
                    transportData.Append((byte)reader.ReadByte());
                }

                TransportPacket newPacket = new TransportPacket(transportData.buffer);

                long streamTime = (InitialTime - ((long)((TimePerFrame * 2) * 27000000)) + LastStamp);
                streamBuffer.SetTime(streamTime);
                while (!streamBuffer.CanAdd(184))
                {
                    long newStreamTime = streamBuffer.NextEventTime;
                    LastStamp += newStreamTime - streamTime;
                    streamTime = newStreamTime;
                    streamBuffer.SetTime(streamTime);
                }
                streamBuffer.AddEvent(184, (long)streamTime);

                newPacket.StreamTime   = (ulong)streamTime;
                LastStamp             += payloadTransmissionTime;
                newPacket.DecoderStamp = (ulong)decoderStamp;
                decoderStamp          += payloadTransmissionTime;
                Packets.AddPacket(newPacket);
            }
        }
示例#49
0
        public void AppendZigBeeType(object data, DataType type)
        {
            if (data == null)
            {
                throw new ArgumentException("You can not append null data to a stream");
            }

            switch (type)
            {
            case DataType.BOOLEAN:
                _buffer[_length++] = (bool)data ? (byte)0x01 : (byte)0x00;
                break;

            case DataType.NWK_ADDRESS:
            case DataType.BITMAP_16_BIT:
            case DataType.SIGNED_16_BIT_INTEGER:
            case DataType.UNSIGNED_16_BIT_INTEGER:
            case DataType.ENUMERATION_16_BIT:
            case DataType.CLUSTERID:
                ushort shortValue = Convert.ToUInt16(data);
                _buffer[_length++] = (byte)(shortValue & 0xFF);
                _buffer[_length++] = (byte)((shortValue >> 8) & 0xFF);
                break;

            case DataType.ENDPOINT:
            case DataType.DATA_8_BIT:
            case DataType.BITMAP_8_BIT:
            case DataType.SIGNED_8_BIT_INTEGER:
            case DataType.UNSIGNED_8_BIT_INTEGER:
            case DataType.ENUMERATION_8_BIT:
                byte byteValue = Convert.ToByte(data);
                _buffer[_length++] = (byte)(byteValue & 0xFF);
                break;

            case DataType.EXTENDED_PANID:
                byte[] panId = BitConverter.GetBytes(((ExtendedPanId)data).Value);
                _buffer[_length++] = panId[0];
                _buffer[_length++] = panId[1];
                _buffer[_length++] = panId[2];
                _buffer[_length++] = panId[3];
                _buffer[_length++] = panId[4];
                _buffer[_length++] = panId[5];
                _buffer[_length++] = panId[6];
                _buffer[_length++] = panId[7];
                break;

            case DataType.IEEE_ADDRESS:
                byte[] address = BitConverter.GetBytes(((IeeeAddress)data).Value);
                _buffer[_length++] = address[0];
                _buffer[_length++] = address[1];
                _buffer[_length++] = address[2];
                _buffer[_length++] = address[3];
                _buffer[_length++] = address[4];
                _buffer[_length++] = address[5];
                _buffer[_length++] = address[6];
                _buffer[_length++] = address[7];
                break;

            case DataType.N_X_ATTRIBUTE_INFORMATION:
                break;

            case DataType.N_X_ATTRIBUTE_RECORD:
                break;

            case DataType.N_X_ATTRIBUTE_REPORT:
                break;

            case DataType.N_X_ATTRIBUTE_REPORTING_CONFIGURATION_RECORD:
                break;

            case DataType.N_X_ATTRIBUTE_SELECTOR:
                break;

            case DataType.N_X_ATTRIBUTE_STATUS_RECORD:
                break;

            case DataType.N_X_EXTENSION_FIELD_SET:
                break;

            case DataType.N_X_NEIGHBORS_INFORMATION:
                break;

            case DataType.N_X_READ_ATTRIBUTE_STATUS_RECORD:
                break;

            case DataType.N_X_UNSIGNED_16_BIT_INTEGER:
                List <ushort> intArray16 = (List <ushort>)data;
                _buffer[_length++] = (byte)intArray16.Count;
                foreach (ushort value in intArray16)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                    _buffer[_length++] = (byte)((value >> 8) & 0xFF);
                }
                break;

            case DataType.N_X_UNSIGNED_8_BIT_INTEGER:
                List <byte> intArrayNX8 = (List <byte>)data;
                _buffer[_length++] = (byte)intArrayNX8.Count;
                foreach (byte value in intArrayNX8)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                }
                break;

            case DataType.UNSIGNED_8_BIT_INTEGER_ARRAY:
                byte[] intArrayN8 = (byte[])data;
                foreach (byte value in intArrayN8)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                }
                break;

            case DataType.X_UNSIGNED_8_BIT_INTEGER:
                List <byte> intArrayX8 = (List <byte>)data;
                foreach (byte value in intArrayX8)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                }
                break;

            case DataType.N_X_ATTRIBUTE_IDENTIFIER:
                List <ushort> intArrayX16 = (List <ushort>)data;
                foreach (ushort value in intArrayX16)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                    _buffer[_length++] = (byte)((value >> 8) & 0xFF);
                }
                break;

            case DataType.N_X_WRITE_ATTRIBUTE_RECORD:
                break;

            case DataType.N_X_WRITE_ATTRIBUTE_STATUS_RECORD:
                break;

            case DataType.OCTET_STRING:
                ByteArray array = (ByteArray)data;
                _buffer[_length++] = ((byte)(array.Size() & 0xFF));
                foreach (byte arrayByte in array.Get())
                {
                    _buffer[_length++] = arrayByte;
                }
                break;

            case DataType.CHARACTER_STRING:
                string str = (string)data;
                _buffer[_length++] = ((byte)(str.Length & 0xFF));
                foreach (byte strByte in Encoding.ASCII.GetBytes((str)))
                {
                    _buffer[_length++] = strByte;
                }
                break;

            case DataType.LONG_OCTET_STRING:
                ByteArray longArray = (ByteArray)data;
                _buffer[_length++] = ((byte)(longArray.Size() & 0xFF));
                _buffer[_length++] = (byte)((longArray.Size() >> 8) & 0xFF);
                foreach (byte arrayByte in longArray.Get())
                {
                    _buffer[_length++] = arrayByte;
                }
                break;

            case DataType.SECURITY_KEY:
                ZigBeeKey securityKey = (ZigBeeKey)data;
                foreach (byte arrayByte in securityKey.Key)
                {
                    _buffer[_length++] = arrayByte;
                }
                break;

            case DataType.BITMAP_24_BIT:
            case DataType.SIGNED_24_BIT_INTEGER:
            case DataType.UNSIGNED_24_BIT_INTEGER:
                uint uint24Value = (uint)data;
                _buffer[_length++] = (byte)(uint24Value & 0xFF);
                _buffer[_length++] = (byte)((uint24Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((uint24Value >> 16) & 0xFF);
                break;

            case DataType.ENUMERATION_32_BIT:
            case DataType.SIGNED_32_BIT_INTEGER:
                int intValue = (int)data;
                _buffer[_length++] = (byte)(intValue & 0xFF);
                _buffer[_length++] = (byte)((intValue >> 8) & 0xFF);
                _buffer[_length++] = (byte)((intValue >> 16) & 0xFF);
                _buffer[_length++] = (byte)((intValue >> 24) & 0xFF);
                break;

            case DataType.BITMAP_32_BIT:
            case DataType.UNSIGNED_32_BIT_INTEGER:
                uint uint32Value = (uint)data;
                _buffer[_length++] = (byte)(uint32Value & 0xFF);
                _buffer[_length++] = (byte)((uint32Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((uint32Value >> 16) & 0xFF);
                _buffer[_length++] = (byte)((uint32Value >> 24) & 0xFF);
                break;

            case DataType.UNSIGNED_48_BIT_INTEGER:
                ulong uint48Value = (ulong)data;
                _buffer[_length++] = (byte)(uint48Value & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 16) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 24) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 32) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 40) & 0xFF);
                break;

            case DataType.UTCTIME:
                break;

            case DataType.ZDO_STATUS:
                _buffer[_length++] = (byte)((ZdoStatus)data);
                break;

            case DataType.ZCL_STATUS:
                _buffer[_length++] = (byte)((ZclStatus)data);
                break;

            case DataType.BYTE_ARRAY:
                ByteArray byteArray = (ByteArray)data;
                _buffer[_length++] = (byte)(byteArray.Size());
                foreach (byte valByte in byteArray.Get())
                {
                    _buffer[_length++] = (byte)(valByte & 0xff);
                }
                break;

            case DataType.ZIGBEE_DATA_TYPE:
                _buffer[_length++] = (byte)((ZclDataType)data).Id;
                break;

            case DataType.FLOAT_32_BIT:
                float  float32      = (float)data;
                byte[] floatBytes   = BitConverter.GetBytes(float32);
                int    float32Value = BitConverter.ToInt32(floatBytes, 0);
                _buffer[_length++] = (byte)(float32Value & 0xFF);
                _buffer[_length++] = (byte)((float32Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((float32Value >> 16) & 0xFF);
                _buffer[_length++] = (byte)((float32Value >> 24) & 0xFF);
                break;

            default:
                throw new ArgumentException("No writer defined in " + this.GetType().Name
                                            + " for " + type.ToString() + " (" + (byte)type + ")");
            }
        }
示例#50
0
        public override void GenerateProgramMap(ByteArray map)
        {
            // stream_type = 0x81					(8 bits)
            map.AppendBits((byte)0x81, 7, 0);

            // reserved = '111b'					(3 bits)
            map.AppendBits((byte)0x7, 2, 0);

            // elementary_PID						(13 bits)
            map.AppendBits(PID, 12, 0);

            // reserved = '1111b'					(4 bits)
            map.AppendBits((byte)0xF, 3, 0);

            // ES_info_length = 0x013 (19 bytes)	(12 bits)
            // Old : ES_info_length = 0x00c (12 bytes)	(12 bits)
            map.AppendBits((ushort)0x013, 11, 0);

            // AC-3 Descriptor
            //		descriptor_tag = 0x05 (registration)	(8 bits)
            map.AppendBits((byte)0x05, 7, 0);

            //		descriptor_length = 0x04				(8 bits)
            map.AppendBits((byte)0x04, 7, 0);

            //		format_identifier = 'AC-3'				(32 bits)
            map.AppendBits((byte)'A', 7, 0);
            map.AppendBits((byte)'C', 7, 0);
            map.AppendBits((byte)'-', 7, 0);
            map.AppendBits((byte)'3', 7, 0);

            // ISO_639 Language Code Descriptor
            //		descriptor_tag = 0x0A (ISO-639)			(8 bits)
            map.AppendBits((byte)0x0A, 7, 0);

            //		descriptor_length = 0x04				(8 bits)
            map.AppendBits((byte)0x04, 7, 0);

            //		ISO_639_language_code					(24 bits)
            map.AppendBits((byte)LanguageCode[0], 7, 0);
            map.AppendBits((byte)LanguageCode[1], 7, 0);
            map.AppendBits((byte)LanguageCode[2], 7, 0);

            //		audio_type = 0x00						(8 bits)
            map.AppendBits((byte)0x00, 7, 0);

            // AC-3_audio_stream_descriptor()
            //      descriptor_tag = 0x81                   (8 bits)
            map.AppendBits((byte)0x81, 7, 0);

            //      descriptor_length = 5                   (8 bits)
            map.AppendBits((byte)0x5, 7, 0);

            //      sample_rate_code                        (3 bits)
            map.AppendBits((byte)descriptorSampleRateCode, 2, 0);

            //      bsid = '01000'                          (5 bits)
            map.AppendBits((byte)0x08, 4, 0);

            //      bit_rate_code                           (6 bits)
            map.AppendBits((byte)bitRateCode, 5, 0);

            //      surround_mode                           (2 bits)
            map.AppendBits((byte)dsurmod, 1, 0);

            //      bsmod                                   (3 bits)
            map.AppendBits((byte)BitStreamMode, 2, 0);

            //      num_channels                            (4 bits)
            map.AppendBits((byte)numChannels, 3, 0);

            //      full_svc (always true for us)           (1 bit)
            map.AppendBit(1);

            //      langcod (always 0 for us)               (8 bits)
            map.AppendBits((byte)0, 7, 0);

            //      mainid (always 0 for us)                (3 bits)
            map.AppendBits((byte)0, 2, 0);

            //      priority (always 3=not specified) for us    (2 bits)
            // TODO : Add a "primaryAudio" flag for this class, if set, then this value will be 1, alternatively, then 2
            map.AppendBits((byte)3, 1, 0);

            //      reserved (all ones)                     (3 bits)
            map.AppendBits((byte)7, 2, 0);
        }
示例#51
0
 public static Sha384Object sha384(ByteArray data)
 {
     return(new Sha384Object((IList <byte>)data));
 }
 public ByteArrayToLowercaseHexText(ByteArray bytes) => _bytes = bytes;
示例#53
0
 public void update(ByteArray newData)
 {
     update((IList <byte>)newData);
 }
示例#54
0
 public static MD5Type @new(ByteArray data)
 {
     return(new MD5Type((IList <byte>)data));
 }
示例#55
0
 public static sha @new(ByteArray data)
 {
     return(new sha((IList <byte>)data));
 }
示例#56
0
        protected override void LoadEncoding(
            )
        {
            OpenFontParser parser;

            {
                PdfDictionary descriptor = Descriptor;
                if (descriptor.ContainsKey(PdfName.FontFile2)) // Embedded TrueType font file (without 'glyf' table).
                {
                    PdfStream fontFileStream = (PdfStream)descriptor.Resolve(PdfName.FontFile2);
                    parser = new OpenFontParser(fontFileStream.Body);
                }
                else if (descriptor.ContainsKey(PdfName.FontFile3))
                {
                    PdfStream fontFileStream  = (PdfStream)descriptor.Resolve(PdfName.FontFile3);
                    PdfName   fontFileSubtype = (PdfName)fontFileStream.Header[PdfName.Subtype];
                    if (fontFileSubtype.Equals(PdfName.OpenType)) // Embedded OpenFont/TrueType font file (with 'glyf' table).
                    {
                        parser = new OpenFontParser(fontFileStream.Body);
                    }
                    else // Unknown.
                    {
                        throw new NotSupportedException("Unknown embedded font file format: " + fontFileSubtype);
                    }
                }
                else
                {
                    parser = null;
                }
            }
            if (parser != null) // Embedded font file.
            {
                // Glyph indexes.
                glyphIndexes = parser.GlyphIndexes;
                if (codes != null &&
                    parser.Metrics.IsCustomEncoding)
                {
                    /*
                     * NOTE: In case of symbolic font,
                     * glyph indices are natively mapped to character codes,
                     * so they must be remapped to Unicode whenever possible
                     * (i.e. when ToUnicode stream is available).
                     */
                    Dictionary <int, int> unicodeGlyphIndexes = new Dictionary <int, int>();
                    foreach (KeyValuePair <int, int> glyphIndexEntry in glyphIndexes)
                    {
                        int code;
                        if (!codes.TryGetValue(new ByteArray(new byte[] { (byte)(int)glyphIndexEntry.Key }), out code))
                        {
                            continue;
                        }

                        unicodeGlyphIndexes[code] = glyphIndexEntry.Value;
                    }
                    glyphIndexes = unicodeGlyphIndexes;
                }
            }

            PdfDataObject encodingObject = BaseDataObject.Resolve(PdfName.Encoding);
            FlagsEnum     flags          = Flags;

            if ((flags & FlagsEnum.Symbolic) != 0 ||
                ((flags & FlagsEnum.Nonsymbolic) == 0 && encodingObject == null)) // Symbolic.
            {
                symbolic = true;

                if (glyphIndexes == null)
                {
                    /*
                     * NOTE: In case no font file is available, we have to synthesize its metrics
                     * from existing entries.
                     */
                    glyphIndexes = new Dictionary <int, int>();
                    PdfArray glyphWidthObjects = (PdfArray)BaseDataObject.Resolve(PdfName.Widths);
                    if (glyphWidthObjects != null)
                    {
                        int code = ((PdfInteger)BaseDataObject[PdfName.FirstChar]).RawValue;
                        foreach (PdfDirectObject glyphWidthObject in glyphWidthObjects)
                        {
                            if (((PdfInteger)glyphWidthObject).RawValue > 0)
                            {
                                glyphIndexes[code] = code;
                            }

                            code++;
                        }
                    }
                }

                if (this.codes == null)
                {
                    Dictionary <ByteArray, int> codes = new Dictionary <ByteArray, int>();
                    foreach (KeyValuePair <int, int> glyphIndexEntry in glyphIndexes)
                    {
                        if (glyphIndexEntry.Value > 0)
                        {
                            int    glyphCharCode = glyphIndexEntry.Key;
                            byte[] charCode      = new byte[] { (byte)glyphCharCode };
                            codes[new ByteArray(charCode)] = glyphCharCode;
                        }
                    }
                    this.codes = new BiDictionary <ByteArray, int>(codes);
                }
            }
            else // Nonsymbolic.
            {
                symbolic = false;

                if (this.codes == null)
                {
                    Dictionary <ByteArray, int> codes;
                    if (encodingObject == null) // Default encoding.
                    {
                        codes = Encoding.Get(PdfName.StandardEncoding).GetCodes();
                    }
                    else if (encodingObject is PdfName) // Predefined encoding.
                    {
                        codes = Encoding.Get((PdfName)encodingObject).GetCodes();
                    }
                    else // Custom encoding.
                    {
                        PdfDictionary encodingDictionary = (PdfDictionary)encodingObject;

                        // 1. Base encoding.
                        PdfName baseEncodingName = (PdfName)encodingDictionary[PdfName.BaseEncoding];
                        if (baseEncodingName == null) // Default base encoding.
                        {
                            codes = Encoding.Get(PdfName.StandardEncoding).GetCodes();
                        }
                        else // Predefined base encoding.
                        {
                            codes = Encoding.Get(baseEncodingName).GetCodes();
                        }

                        // 2. Differences.
                        LoadEncodingDifferences(encodingDictionary, codes);
                    }
                    this.codes = new BiDictionary <ByteArray, int>(codes);
                }

                if (glyphIndexes == null)
                {
                    /*
                     * NOTE: In case no font file is available, we have to synthesize its metrics
                     * from existing entries.
                     */
                    glyphIndexes = new Dictionary <int, int>();
                    PdfArray glyphWidthObjects = (PdfArray)BaseDataObject.Resolve(PdfName.Widths);
                    if (glyphWidthObjects != null)
                    {
                        ByteArray charCode = new ByteArray(
                            new byte[]
                            { (byte)(int)((PdfInteger)BaseDataObject[PdfName.FirstChar]).RawValue }
                            );
                        foreach (PdfDirectObject glyphWidthObject in glyphWidthObjects)
                        {
                            if (((PdfInteger)glyphWidthObject).RawValue > 0)
                            {
                                int code;
                                if (codes.TryGetValue(charCode, out code))
                                {
                                    glyphIndexes[code] = (int)charCode.Data[0];
                                }
                            }
                            charCode.Data[0]++;
                        }
                    }
                }
            }
        }
示例#57
0
        public virtual void ReadExternal(IDataInput input)
        {
            List <byte> byteList1 = this.ReadFlags(input);
            int         bits1     = 0;

            for (int index = 0; index < byteList1.Count; ++index)
            {
                byte num = byteList1[index];
                if (index == 0)
                {
                    if (((int)num & 1) != 0)
                    {
                        this.Body = input.ReadObject();
                    }
                    if (((int)num & 2) != 0)
                    {
                        this.ClientId = (string)input.ReadObject();
                    }
                    if (((int)num & 4) != 0)
                    {
                        this.Destination = (string)input.ReadObject();
                    }
                    if (((int)num & 8) != 0)
                    {
                        this.Headers = input.ReadObject() as AsObject;
                    }
                    if (((int)num & 16) != 0)
                    {
                        this.MessageId = (string)input.ReadObject();
                    }
                    if (((int)num & 32) != 0)
                    {
                        this.Timestamp = Convert.ToInt64(input.ReadObject());
                    }
                    if (((int)num & 64) != 0)
                    {
                        this.TimeToLive = Convert.ToInt64(input.ReadObject());
                    }
                    bits1 = 7;
                }
                else if (index == 1)
                {
                    if (((int)num & 1) != 0)
                    {
                        this.ClientIdBytes = (ByteArray)input.ReadObject();
                    }
                    if (((int)num & 2) != 0)
                    {
                        this.MessageIdBytes = (ByteArray)input.ReadObject();
                    }
                    bits1 = 2;
                }
                this.ReadRemaining(input, (int)num, bits1);
            }
            List <byte> byteList2 = this.ReadFlags(input);

            for (int index = 0; index < byteList2.Count; ++index)
            {
                byte num   = byteList2[index];
                int  bits2 = 0;
                if (index == 0)
                {
                    if (((int)num & 1) != 0)
                    {
                        this.CorrelationId = (string)input.ReadObject();
                    }
                    if (((int)num & 2) != 0)
                    {
                        this.CorrelationIdBytes = (ByteArray)input.ReadObject();
                    }
                    bits2 = 2;
                }
                this.ReadRemaining(input, (int)num, bits2);
            }
        }
示例#58
0
        public override void Decode(ByteArray array)
        {
            byte type = array.ReadByte();

            MaximumStreams = array.ReadVariableInteger();
        }
示例#59
0
 internal virtual long GetNext(ByteArray array, long index)
 {
     return(All48Bits(array, index, NEXT_OFFSET));
 }
示例#60
0
 internal virtual void ClearIndex(ByteArray array, long relGroupId)
 {
     array.Set(relGroupId, DefaultValue);
 }