public void Serialize(ByteStreamWriter writer) { writer.WriteInteger(id); int changeMask = 0; if (healthDirty) { changeMask = changeMask | maskOfHealthChange; } if (positionDirty) { changeMask = changeMask | maskOfPositionChange; } writer.WriteByte((byte)changeMask); if (healthDirty) { writer.WriteFloat(power); } if (positionDirty) { writer.WriteVector2(position); } }
public override void Save(bool freshWithoutChanged = false) { FileStream fs = DataFile.Open(FileMode.Create); ByteStreamWriter bsw = new ByteStreamWriter(fs); int w = Value.GetLength(1), h = Value.GetLength(0); bsw.Write(BitConverter.GetBytes(w), 4); bsw.Write(BitConverter.GetBytes(h), 4); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { bsw.Write(Value[i, j].power); } } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { bsw.Write((byte)Value[i, j].direction); } } bsw.Flush(); bsw.Close(); fs.Flush(); fs.Close(); Changed = false; }
/// <summary> /// Dict is the dictionary file /// Delta is the diff file /// Sout is the stream for output /// </summary> /// <param name="dict">Dictionary</param> /// <param name="delta">Target file / Diff / Delta file</param> /// <param name="sout">Output Stream</param> public VCDecoder(Stream dict, Stream delta, Stream sout) { this.delta = new ByteStreamReader(delta); this.dict = new ByteStreamReader(dict); this.sout = new ByteStreamWriter(sout); isStarted = false; }
public VCDecoder(IByteBuffer dict, IByteBuffer delta, Stream sout) { this.delta = delta; this.dict = dict; this.sout = new ByteStreamWriter(sout); isStarted = false; }
public Vector2 m_point; //only when server sends public override void Serialize(ByteStreamWriter writer) { base.Serialize(writer); writer.WriteInteger(m_who); writer.WriteVector2(m_direction); writer.WriteVector2(m_point); }
/// <summary> /// Sends an event to a client. /// </summary> /// <param name="e">Event to send.</param> /// <param name="connectionId">Target client's connection id</param> /// <param name="reliable">Is it reliable event</param> /// <param name="internalResend">If <c>false</c> this event will be added to reliable events queue as a new event</param> /// <returns><c>true</c> if the target client is connected</returns> public bool Send(EventBase e, int connectionId, bool reliable = false, bool internalResend = false) { ByteStreamWriter stream = new ByteStreamWriter(); stream.WriteByte(reliable ? ( byte )MsgFlags.ReliableEvent : ( byte )MsgFlags.UnreliableEvent); stream.WriteByte(e.GetId()); e.Serialize(stream); Connection c = m_server.GetConnectionById(connectionId); if (c != null) { c.Send(stream.GetBytes()); if (reliable && !internalResend && e is ReliableEventBase) { ReliableEventBase reb = e as ReliableEventBase; m_reliablesToRepeat[reb.m_reliableEventId] = new REventIdPair(connectionId, reb); } return(true); } else { return(false); } }
public override void Serialize(ByteStreamWriter writer) { writer.WriteInteger(states.Count); foreach (PlayerState playerState in states) { playerState.Serialize(writer); } }
public override void Serialize(ByteStreamWriter writer) { writer.WriteInteger(m_sessionId); writer.WriteBool(m_actuallySpawned); if (m_actuallySpawned) { writer.WriteVector2(m_startPosition); } }
/// <summary> /// Starts handshake process. /// </summary> /// <param name="receivePort">The port server should send data to.</param> public void HandshakeStepOne(int receivePort) { ByteStreamWriter writer = new ByteStreamWriter(); writer.WriteByte((byte)MsgFlags.ConnectionRequest); writer.WriteByte((byte)HandshakeMessage.SYN); writer.WriteInteger(receivePort); m_sender.Send(writer.GetBytes()); State = ConnectionState.Connecting; }
private void HandshakeStepTwo(BaseConnectionEntity con) { ByteStreamWriter writer = new ByteStreamWriter(); writer.WriteByte((byte)MsgFlags.ConnectionRequest); writer.WriteByte((byte)HandshakeMessage.SYNACK); writer.WriteInteger(con.m_connectionId); con.m_sender.Send(writer.GetBytes()); con.m_sender.Send(writer.GetBytes()); con.m_sender.Send(writer.GetBytes()); con.m_sender.Send(writer.GetBytes()); }
/// <summary> /// Sends an event to a server. /// </summary> /// <param name="e">Event to send.</param> /// <param name="reliable">Is it reliable event</param> /// <param name="internalResend">If <c>false</c> this event will be added to reliable events queue as a new event</param> /// <returns><c>true</c> if the target client is connected</returns> public void Send(EventBase e, bool reliable = false, bool internalResend = false) { ByteStreamWriter stream = new ByteStreamWriter(); stream.WriteByte(reliable ? (byte)MsgFlags.ReliableEvent : (byte)MsgFlags.UnreliableEvent); stream.WriteByte(e.GetId()); e.Serialize(stream); m_client.Send(stream.GetBytes()); if (reliable && !internalResend && e is ReliableEventBase) { ReliableEventBase reb = e as ReliableEventBase; m_reliablesToRepeat[reb.m_reliableEventId] = reb; } }
/// <summary> /// The easy public structure for encoding into a vcdiff format /// Simply instantiate it with the proper streams and use the Encode() function. /// Does not check if data is equal already. You will need to do that. /// Returns VCDiffResult: should always return success, unless either the dict or the target streams have 0 bytes /// See the VCDecoder for decoding vcdiff format /// </summary> /// <param name="dict">The dictionary (previous data)</param> /// <param name="target">The new data</param> /// <param name="sout">The output stream</param> /// <param name="maxBufferSize">The maximum buffer size for window chunking. It is in Megabytes. 2 would mean 2 megabytes etc. Default is 1.</param> public VCCoder(Stream dict, Stream target, Stream sout, int maxBufferSize = 1) { if (maxBufferSize <= 0) { maxBufferSize = 1; } oldData = new ByteStreamReader(dict); newData = new ByteStreamReader(target); this.sout = new ByteStreamWriter(sout); hasher = new RollingHash(BlockHash.BlockSize); bufferSize = maxBufferSize * 1024 * 1024; }
public void Shutdown() { ByteStreamWriter writer = new ByteStreamWriter(); writer.WriteByte((byte)MsgFlags.ConnectionRequest); writer.WriteByte((byte)HandshakeMessage.Disconnect); writer.WriteInteger(ConnectionId); for (int i = 0; i < 5; ++i) { Send(writer); } m_client.Shutdown(); }
/// <summary> /// The main decoder loop for the data /// </summary> /// <param name="w">the window decoder</param> /// <param name="dictionary">the dictionary data</param> /// <param name="target">the target data</param> /// <param name="sout">the out stream</param> /// <param name="customTable">custom table if any. Default is null.</param> public BodyDecoder(WindowDecoder w, IByteBuffer dictionary, IByteBuffer target, ByteStreamWriter sout, CustomCodeTableDecoder customTable = null) { if (customTable != null) { this.customTable = customTable; addressCache = new AddressCache((byte)customTable.NearSize, (byte)customTable.SameSize); } else { addressCache = new AddressCache(); } window = w; this.sout = sout; this.dict = dictionary; this.target = target; targetData = new List <byte>(); }
public byte[] Encode() { using (ByteStreamWriter writer = new ByteStreamWriter()) { writer.WriteShort(data.Length + 35); //version(2)+roleId(8)+SessionID(4)+sequence(8)+gameVersion(2)+resVersion(4)+platform(1)+protocalCode(4) = 33 writer.WriteShort(version); writer.WriteLong(playerId); writer.WriteInt(sessionId); writer.WriteLong(sequence); writer.WriteShort(gameVersion); writer.WriteInt(resVersion); writer.WriteByte(platform); writer.WriteInt(protocalCode); writer.WriteBytes(data); //Jiawen: optimise GetBuff function to save some new operations. return(writer.GetBuffer()); } }
/// <summary> /// Sends a confirmation of receiving the Connection ID to server (finalizes the connection on the Client side) /// </summary> /// <param name="connectionId">The connection identifier.</param> public void HandshakeStepThree(int connectionId) { ByteStreamWriter writer = new ByteStreamWriter(); writer.WriteByte((byte)MsgFlags.ConnectionRequest); writer.WriteByte((byte)HandshakeMessage.ACK); writer.WriteInteger(connectionId); for (int i = 0; i < 5; ++i) { m_sender.Send(writer.GetBytes()); } ConnectionId = connectionId; State = ConnectionState.Connected; Network.Log(State + ", " + ConnectionId); }
public byte[] Encode() { using (ByteStreamWriter writer = new ByteStreamWriter()) { writer.WriteShort(data.Length + 48); //version(2)+roleId(8)+SessionID(4)+sequence(8)+ack(8)+protocalCode(4)+endSequence(8)+checkSum(4) = 46 writer.WriteShort(version); writer.WriteLong(playerId); writer.WriteInt(sessionId); writer.WriteLong(sequence); writer.WriteLong(ack); writer.WriteInt(protocalCode); writer.WriteLong(endSequence); //TODO: calculate checkSum. writer.WriteInt(checkSum); writer.WriteBytes(data); //Jiawen: optimise GetBuff function to save some new operations. return(writer.GetBuffer()); } }
public void Output(ByteStreamWriter sout) { int lengthOfDelta = CalculateLengthOfTheDeltaEncoding(); int windowSize = lengthOfDelta + 1 + VarIntBE.CalcInt32Length((int)dictionarySize) + VarIntBE.CalcInt32Length(0); VarIntBE.CalcInt32Length(lengthOfDelta); //Google's Checksum Implementation Support if (hasChecksum) { sout.writeByte((byte)VCDiffWindowFlags.VCDSOURCE | (byte)VCDiffWindowFlags.VCDCHECKSUM); //win indicator } else { sout.writeByte((byte)VCDiffWindowFlags.VCDSOURCE); //win indicator } VarIntBE.AppendInt32((int)dictionarySize, sout); //dictionary size VarIntBE.AppendInt32(0, sout); //dictionary start position 0 is default aka encompass the whole dictionary VarIntBE.AppendInt32(lengthOfDelta, sout); //length of delta //begin of delta encoding Int64 sizeBeforeDelta = sout.Position; VarIntBE.AppendInt32((int)targetLength, sout); //final target length after decoding sout.writeByte(0x00); //uncompressed // [Here is where a secondary compressor would be used // if the encoder and decoder supported that feature.] //non interleaved then it is separata areas for each type if (!interleaved) { VarIntBE.AppendInt32(dataForAddAndRun.Count, sout); //length of add/run VarIntBE.AppendInt32(instructionAndSizes.Count, sout); //length of instructions and sizes VarIntBE.AppendInt32(addressForCopy.Count, sout); //length of addresses for copys //Google Checksum Support if (hasChecksum) { VarIntBE.AppendInt64(checksum, sout); } sout.writeBytes(dataForAddAndRun.ToArray()); //data section for adds and runs sout.writeBytes(instructionAndSizes.ToArray()); //data for instructions and sizes sout.writeBytes(addressForCopy.ToArray()); //data for addresses section copys } else { //interleaved everything is woven in and out in one block VarIntBE.AppendInt32(0, sout); //length of add/run VarIntBE.AppendInt32(instructionAndSizes.Count, sout); //length of instructions and sizes + other data for interleaved VarIntBE.AppendInt32(0, sout); //length of addresses for copys //Google Checksum Support if (hasChecksum) { VarIntBE.AppendInt64(checksum, sout); } sout.writeBytes(instructionAndSizes.ToArray()); //data for instructions and sizes, in interleaved it is everything } //end of delta encoding Int64 sizeAfterDelta = sout.Position; if (lengthOfDelta != sizeAfterDelta - sizeBeforeDelta) { Console.WriteLine("Delta output length does not match"); } dataForAddAndRun.Clear(); instructionAndSizes.Clear(); addressForCopy.Clear(); if (targetLength == 0) { Console.WriteLine("Empty target window"); } addrCache = new AddressCache(); }
public override void Serialize(ByteStreamWriter writer) { writer.WriteInteger(m_reliableEventId); }
/// <summary> /// Save event's data into a bytestream. /// </summary> /// <param name="writer">The writer.</param> public abstract void Serialize(ByteStreamWriter writer);
public override void Serialize(ByteStreamWriter writer) { }
public override void Serialize(ByteStreamWriter writer) { writer.WriteVector2(m_direction); writer.WriteInteger(m_sessionId); }
/// <summary> /// Sends raw bytestream to server /// </summary> /// <param name="stream">The stream.</param> public void Send(ByteStreamWriter stream) { m_client.Send(stream.GetBytes()); }
/// <summary> /// Encodes the data using the settings from initialization /// </summary> /// <param name="newData">the target data</param> /// <param name="sout">the out stream</param> public void EncodeChunk(IByteBuffer newData, ByteStreamWriter sout) { uint checksum = 0; ///If checksum needed ///Generate Adler32 checksum for the incoming bytes if (hasChecksum) { newData.Position = 0; byte[] bytes = newData.ReadBytes((int)newData.Length); checksum = Checksum.ComputeAdler32(bytes); bytes = null; } windowEncoder = new WindowEncoder(oldData.Length, checksum, interleaved, hasChecksum); oldData.Position = 0; newData.Position = 0; this.newData = newData; long nextEncode = newData.Position; long targetEnd = newData.Length; long startOfLastBlock = targetEnd - BlockHash.BlockSize; long candidatePos = nextEncode; //create the first hash ulong hash = hasher.Hash(newData.PeekBytes(BlockHash.BlockSize)); while (true) { //if less than block size exit and then write as an ADD if (newData.Length - nextEncode < BlockHash.BlockSize) { break; } //try and encode the copy and add instructions that best match long bytesEncoded = EncodeCopyForBestMatch(hash, candidatePos, nextEncode, targetEnd); if (bytesEncoded > 0) { nextEncode += bytesEncoded; candidatePos = nextEncode; if (candidatePos > startOfLastBlock) { break; } newData.Position = candidatePos; //cannot use rolling hash since we skipped so many hash = hasher.Hash(newData.ReadBytes(BlockHash.BlockSize)); } else { if (candidatePos + 1 > startOfLastBlock) { break; } //update hash requires the first byte of the last hash as well as the byte that is first byte pos + blockSize //in order to properly calculate the rolling hash newData.Position = candidatePos; byte peek0 = newData.ReadByte(); newData.Position = candidatePos + BlockHash.BlockSize; byte peek1 = newData.ReadByte(); hash = hasher.UpdateHash(hash, peek0, peek1); candidatePos++; } } //Add the rest of the data that was not encoded if (nextEncode < newData.Length) { int len = (int)(newData.Length - nextEncode); newData.Position = nextEncode; windowEncoder.Add(newData.ReadBytes(len)); } //output the final window windowEncoder.Output(sout); }
public ByteStreamReader(ByteStreamWriter writer) : this(writer.GetBytes()) { }