public override PacketData GetBytes(IHeader header, PacketData packetData) { var udpHeader = (UdpHeader)header; var currentData = new List<byte>(); currentData.AddRange(GetBytes(udpHeader.SourcePort)); currentData.AddRange(GetBytes(udpHeader.DestinationPort)); currentData.AddRange(GetBytes((ushort)(UdpHeaderProperty.Size + packetData.Data.Count))); currentData.AddRange(new byte[] { 0, 0 }); //+ crc List<byte> crcData = GetPseudoHeaderBytes(udpHeader, (uint)(packetData.Data.Count + UdpHeaderProperty.Size)); crcData.AddRange(currentData); crcData.AddRange(packetData.Data); if (crcData.Count % 2 == 1) { crcData.Add(0); } byte[] crc = Checksum.GetCrc(crcData.ToArray()); currentData[6] = crc[1]; currentData[7] = crc[0]; //+ currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var ipHeader = (IPHeader)header; var currentData = new List<byte>(); currentData.Add((byte)((ipHeader.VersionIHL << 4) | 5)); currentData.Add(ipHeader.TypeOfService); //currentData.AddRange(GetBytes((UInt16)(packetData.Data.Count + 20))); currentData.AddRange(GetBytes(ipHeader.TotalLength)); currentData.AddRange(GetBytes(ipHeader.Identification)); //++ flags (3 bits-- left to right) //Bit 0: reserved, must be zero //Bit 1: (DF) 0 = May Fragment, 1 = Don't Fragment. //Bit 2: (MF) 0 = Last Fragment, 1 = More Fragments. //++ offset (13 bits) currentData.AddRange(GetBytes(ipHeader.FlagsFragmentOffset)); currentData.Add(ipHeader.TTL); currentData.Add(ipHeader.Protocol); currentData.AddRange(new byte[] { 0, 0 }); currentData.AddRange(ipHeader.SourceAddress.GetBytes()); currentData.AddRange(ipHeader.DestinationAddress.GetBytes()); byte[] crc = GetCrc(currentData.ToArray()); currentData[10] = crc[1]; currentData[11] = crc[0]; currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var imageHeader = (ImageHeader)header; var currentData = new List<byte>(); currentData.Add(imageHeader.Operation); currentData.AddRange(imageHeader.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var icmpEchoHeader = (IcmpEchoHeader)header; var currentData = new List<byte>(); currentData.AddRange(GetBytes(icmpEchoHeader.Identifier)); currentData.AddRange(GetBytes(icmpEchoHeader.SequenceNumber)); currentData.AddRange(icmpEchoHeader.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var ethernetHeader = (EthernetHeader)header; var currentData = new List<byte>(); currentData.AddRange(ethernetHeader.Destination.GetBytes()); currentData.AddRange(ethernetHeader.Source.GetBytes()); currentData.AddRange(ethernetHeader.TypeOrLength.GetBytes()); currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { return packetData; var ipv6_header = (IPv6Header)header; var currentData = new List<byte>(); //++ more here currentData.AddRange(ipv6_header.SourceAddress.GetBytes()); currentData.AddRange(ipv6_header.DestinationAddress.GetBytes()); currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages) { foreach (var eventData in messages) { var packetData = Encoding.UTF8.GetString(eventData.GetBytes()); var packetContext = new PacketData(MakeUri(eventData), packetData); await _hostedMiddeMiddleware.Invoke(packetContext); } await context.CheckpointAsync(); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var icmpHeader = (IcmpHeader)header; var currentData = new List<byte>(); currentData.AddRange(GetBytes(icmpHeader.Type)); currentData.AddRange(GetBytes(icmpHeader.Code)); currentData.AddRange(new byte[] { 0, 0 }); currentData.AddRange(packetData.Data); byte[] crc = Checksum.GetCrc(currentData.ToArray()); currentData[2] = crc[1]; currentData[3] = crc[0]; return packetData.UpdateData(currentData); }
public void updateAlertToOPCLabel(PacketData data, Dictionary<string, Dictionary<string, uint>> handles) { if (handles.ContainsKey(data.moduleID)) { Dictionary<string, uint> moduleHandle = handles[data.moduleID]; int pos = data.alertPos; int value = data.alertValue; if (moduleHandle.ContainsKey(data.resolvePos(pos))) { deactive(); OPClib.UpdateTag(moduleHandle[data.resolvePos(pos)], data.transformValue(value,pos), 192); } } }
public override PacketData GetBytes(IHeader header, PacketData packetData) { if (!Collection.IsNullOrEmpty(packetData.Data)) { //TODO: if this becomes iterative, this will have to change throw new InvalidOperationException("There should never be data after the TLV area of an OSPF LLS data block"); } var ospfLlsDataBlockTlv = (OspfLlsDataBlockTlv)header; var currentData = new List<byte>(); currentData.AddRange(GetBytes(ospfLlsDataBlockTlv.Type)); currentData.AddRange(GetBytes(ospfLlsDataBlockTlv.Length)); currentData.AddRange(ospfLlsDataBlockTlv.Value); return packetData.UpdateData(currentData); }
private async Task ReceiveClient(TcpClient client, CancellationToken cancellationToken) { var receiveBuffer = new byte[4096]; var receiveIndex = 0; var hasError = false; while (!cancellationToken.IsCancellationRequested && _isStarted && !hasError) { try { var stream = client.GetStream(); var bytesRead = await stream.ReadAsync(receiveBuffer, receiveIndex, receiveBuffer.Length - receiveIndex, cancellationToken); if (bytesRead <= 0) { break; } receiveIndex += bytesRead; // look for the last newline char for (var i = receiveIndex; i >= 0; --i) { if (receiveBuffer[i] == '\n') { var slice = new byte[i]; Buffer.BlockCopy(receiveBuffer, 0, slice, 0, i); Buffer.BlockCopy(receiveBuffer, i+1, receiveBuffer, 0, receiveIndex - i); receiveIndex = 0; var packetString = Encoding.UTF8.GetString(slice); var context = new PacketData(MakeUri((IPEndPoint)client.Client.RemoteEndPoint), packetString); await _hostedMiddleware.Invoke(context); break; } } } catch (Exception) { hasError = true; } } client.Close(); }
private async Task Listen(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested && _isStarted) { var result = await _udpClient.ReceiveAsync(); var packetString = Encoding.UTF8.GetString(result.Buffer); var context = new PacketData(MakeUri(result.RemoteEndPoint), packetString); try { await _hostedMiddleware.Invoke(context); } catch (Exception) { // todo: trace } } }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var ripPreambleHeader = (RipPreambleHeader)header; var currentData = new List<byte>(); currentData.Add(ripPreambleHeader.command); currentData.Add(ripPreambleHeader.Version); currentData.AddRange(GetBytes(ripPreambleHeader.Domain)); foreach (var ripDataHeader in ripPreambleHeader.DataArray) { currentData.AddRange(GetBytes(ripDataHeader.AddressFamily)); currentData.AddRange(GetBytes(ripDataHeader.RouteTag)); currentData.AddRange(ripDataHeader.Network.GetBytes()); currentData.AddRange(ripDataHeader.Mask.GetBytes()); currentData.AddRange(ripDataHeader.NextHop.GetBytes()); currentData.AddRange(GetBytes(ripDataHeader.Metric)); } return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var ospfDBDHeader = (OspfDbdHeader)header; if (ospfDBDHeader.LsaList != null) { foreach (var ospfLsaHeader in ospfDBDHeader.LsaList) { packetData = Controller.GetSingletonHandler("OSPFLSA").GetBytes(ospfLsaHeader, packetData); } } var currentData = new List<byte>(); currentData.AddRange(GetBytes(ospfDBDHeader.Mtu)); currentData.AddRange(GetBytes(ospfDBDHeader.Options)); currentData.AddRange(GetBytes(ospfDBDHeader.Flags)); currentData.AddRange(GetBytes(ospfDBDHeader.SequenceNumber)); currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { ushort size = (ushort)packetData.Data.Count; var ospfLsaHeader = (OspfLsaHeader)header; var currentData = new List<byte>(); currentData.AddRange(GetBytes(ospfLsaHeader.LSAge)); currentData.AddRange(GetBytes(ospfLsaHeader.Options)); currentData.AddRange(GetBytes(ospfLsaHeader.LSType)); currentData.AddRange(ospfLsaHeader.LSID.GetBytes()); currentData.AddRange(ospfLsaHeader.AdvertisingRouter.GetBytes()); currentData.AddRange(GetBytes(ospfLsaHeader.SequenceNumber)); currentData.AddRange(new byte[] { 0, 0 }); currentData.AddRange(GetBytes((ushort)(20 + size))); byte[] crc = Nalarium.Checksum.GetCrc(currentData.ToArray()); currentData[16] = crc[1]; currentData[17] = crc[0]; currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var arpHeader = (ArpHeader)header; var currentData = new List<byte>(); currentData.AddRange(GetBytes(arpHeader.HardwareType)); currentData.AddRange(GetBytes(arpHeader.ProtocolType)); currentData.Add(arpHeader.HardwareSize); currentData.Add(arpHeader.ProtocolSize); currentData.AddRange(GetBytes(arpHeader.Operation)); currentData.AddRange(arpHeader.SourceMacAddress.GetBytes()); currentData.AddRange(arpHeader.SourceIPAddress.GetBytes()); currentData.AddRange(arpHeader.DestinationMacAddress.GetBytes()); currentData.AddRange(arpHeader.DestinationIPAddress.GetBytes()); currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var ospfHelloHeader = (OspfHelloHeader)header; var currentData = new List<byte>(); currentData.AddRange(GetNotReversedBytes(ospfHelloHeader.Mask)); currentData.AddRange(GetBytes(ospfHelloHeader.Interval)); currentData.Add(ospfHelloHeader.Options); currentData.Add(ospfHelloHeader.RouterPriority); currentData.AddRange(GetBytes(ospfHelloHeader.RouterDeadInterval)); currentData.AddRange(ospfHelloHeader.Dr.GetBytes()); currentData.AddRange(ospfHelloHeader.Bdr.GetBytes()); if (ospfHelloHeader.Neighbor != null) { foreach (IPAddress neighbor in ospfHelloHeader.Neighbor) { currentData.AddRange(neighbor.GetBytes()); } } currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public void updateToOPCLabel(PacketData data, Dictionary<string,Dictionary<string,uint>> handles) { if (handles.ContainsKey(data.moduleID)) { Dictionary<string, uint> moduleHandle = handles[data.moduleID]; foreach (KeyValuePair<string, uint> handle in moduleHandle) { if (data.packetDataMap.ContainsKey(handle.Key)) { //System.Runtime.InteropServices.FILETIME f = new System.Runtime.InteropServices.FILETIME(); deactive(); if (!handle.Key.StartsWith("DO")) { OPClib.UpdateTag(handle.Value, data.packetDataMap[handle.Key], 192);//, System.Runtime.InteropServices.FILETIME); } // LogUtil.writeLog(LogUtil.getFileName(), "[" + DateTime.Now.ToString() + "]: OPC标签更新"); } } } }
protected override void AcceptHandoff(string deviceID, string nextHandlerName, PacketData packetData, Value[] parameterArray) { var headerList = CatalogHeaderListInBranch(nextHandlerName, parameterArray); packetData = GeneratePacketData(packetData, headerList.ToArray()); parameterArray = Controller.OverrideDefaultValueData(parameterArray, Value.Raw("IPHeader:TypeOfService", (byte)0), Value.Raw("IPHeader:TTL", (byte)128), Value.Raw("IPHeader:SourceAddress", Controller.DeviceConfigurationMap[deviceID].PrimaryIPConfiguration.Address), Value.Raw("IPHeader:Protocol", (byte)1)); //++ send to system module for ip packaging var echoHeader = (IcmpEchoHeader)headerList.Single(p => p is IcmpEchoHeader); var timer = new Timer { Interval = 1000 }; var id = new Tuple<int, int>(echoHeader.Identifier, echoHeader.SequenceNumber); var then = DateTime.Now; timer.Elapsed += (s, e) => { if ((DateTime.Now - then).Seconds > 4) { lock (_sequenceTrackingMap) { timer.Stop(); _sequenceTrackingMap.Remove(id); Log.Write("ICMP", "ECHOREQUESTTIMEOUT", echoHeader.Identifier + "," + echoHeader.SequenceNumber); } } }; lock (_sequenceTrackingMap) { _sequenceTrackingMap.Add(id, timer); Log.Write("ICMP", "ECHOREQUEST", echoHeader.Identifier + "," + echoHeader.SequenceNumber); } timer.Start(); Handoff(deviceID, typeof(IPHeader), packetData, parameterArray); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var ospfLlsDataBlockHeader = (OspfLlsDataBlockHeader)header; var currentData = new List<byte>(); currentData.AddRange(new byte[] { 0, 0 }); var size = (ushort)(packetData.Data.Count + 4); packetData.AddProperty("OspfLlsDataBlockHeaderSize", size); currentData.AddRange(GetBytes((ushort)(size / 4))); byte[] crc = Checksum.GetCrc(currentData.ToArray()); currentData[0] = 0xff; currentData[1] = 0xf6; //foreach (var ospfLlsDataBlockTlv in OspfLlsDataBlockHeader.OspfLlsDataBlockTlv) //{ // var subData = new List<byte>(); // Controller.GetSingletonHandler("OSPFLLSDATABLOCKTLV").GetBytes(ospfLlsDataBlockTlv, subData); // currentData.AddRange(subData); //} currentData.AddRange(packetData.Data); return packetData.UpdateData(currentData); }
public override PacketData GetBytes(IHeader header, PacketData packetData) { var ospfHeader = (OspfHeader)header; var currentData = new List<byte>(); currentData.Add(ospfHeader.Version); currentData.Add(ospfHeader.Type); byte[] array = GetBytes((UInt16)(packetData.Data.Count + 24 - packetData.GetProperty<ushort>("OspfLlsDataBlockHeaderSize"))); currentData.AddRange(array); currentData.AddRange(GetNotReversedBytes(ospfHeader.RouterID)); currentData.AddRange(GetBytes(ospfHeader.AreaID)); //currentData.AddRange(new byte[] { 1, 2 }); //currentData.AddRange(new byte[] { 3, 4 }); //currentData.AddRange(new byte[] { 5, 6, 7, 8 }); //currentData.AddRange(new byte[] { 9, 0xa, 0xb, 0xc }); currentData.AddRange(new byte[] { 0, 0 }); currentData.AddRange(new byte[] { 0, 0 }); currentData.AddRange(new byte[] { 0, 0, 0, 0 }); currentData.AddRange(new byte[] { 0, 0, 0, 0 }); currentData.AddRange(packetData.Data); byte[] crc = Checksum.GetCrc(currentData.ToArray()); currentData[12] = crc[1]; currentData[13] = crc[0]; return packetData.UpdateData(currentData); }
public ServerPlayerPositionAndLookPacket(PacketData data) : base(data) { } // packet id should be set correctly if this ctor is used
public ResponsePacket(PacketData data) : base(data) { }
/// <summary> /// 构造 /// </summary> /// <param name="source"></param> /// <param name="type"></param> /// <param name="data"></param> public OutputTunnelPacket(TunnelPipeline source, byte[] header, TunnelPacketType type, PacketData data) : base(source) { Type = type; this.header = header; this.Length = data?.Size ?? 0; this.data = data; HeaderSerializer.Serialize((int)type, data?.Size ?? 0, header); }
void test_reliability_system() { const uint MaximumSequence = 255; Debug.Log(ReliabilitySystem.bit_index_for_sequence(255, 1, MaximumSequence)); ///////////////////////////////// print("check generate ack bits"); PacketQueue packetQueue = new PacketQueue(); for (uint i = 0; i < 32; ++i) { PacketData data = new PacketData(); data.sequence = i; packetQueue.insert_sorted(data, MaximumSequence); } packetQueue.verify_sorted(MaximumSequence); if (ReliabilitySystem.generate_ack_bits(32, ref packetQueue, MaximumSequence) == 0xFFFFFFFF) { Debug.Log("OK"); } if (ReliabilitySystem.generate_ack_bits(31, ref packetQueue, MaximumSequence) == 0x7FFFFFFF) { Debug.Log("OK"); } if (ReliabilitySystem.generate_ack_bits(33, ref packetQueue, MaximumSequence) == 0xFFFFFFFE) { Debug.Log("OK"); } if (ReliabilitySystem.generate_ack_bits(16, ref packetQueue, MaximumSequence) == 0x0000FFFF) { Debug.Log("OK"); } if (ReliabilitySystem.generate_ack_bits(48, ref packetQueue, MaximumSequence) == 0xFFFF0000) { Debug.Log("OK"); } ///////////////////////////////// print("check generate ack bits with wrap"); packetQueue.Clear(); for (uint i = 255 - 31; i <= 255; ++i) { PacketData data = new PacketData(); data.sequence = i; packetQueue.insert_sorted(data, MaximumSequence); } packetQueue.verify_sorted(MaximumSequence); if (packetQueue.Count == 32) { Debug.Log("ack wrap ok"); } ; if (ReliabilitySystem.generate_ack_bits(0, ref packetQueue, MaximumSequence) == 0xFFFFFFFF) { Debug.Log("ack wrap ok"); } ; if (ReliabilitySystem.generate_ack_bits(255, ref packetQueue, MaximumSequence) == 0x7FFFFFFF) { Debug.Log("ack wrap ok"); } ; if (ReliabilitySystem.generate_ack_bits(1, ref packetQueue, MaximumSequence) == 0xFFFFFFFE) { Debug.Log("ack wrap ok"); } ; if (ReliabilitySystem.generate_ack_bits(240, ref packetQueue, MaximumSequence) == 0x0000FFFF) { Debug.Log("ack wrap ok"); } ; if (ReliabilitySystem.generate_ack_bits(16, ref packetQueue, MaximumSequence) == 0xFFFF0000) { Debug.Log("ack wrap ok"); } ; print("check process ack (1)"); PacketQueue pendingAckQueue = new PacketQueue(); for (uint i = 0; i < 33; ++i) { PacketData data = new PacketData(); data.sequence = i; data.time = 0.0f; pendingAckQueue.insert_sorted(data, MaximumSequence); } pendingAckQueue.verify_sorted(MaximumSequence); PacketQueue ackedQueue = new PacketQueue(); List <uint> acks = new List <uint>(); float rtt = 0.0f; uint acked_packets = 0; ReliabilitySystem.process_ack(32, 0xFFFFFFFF, ref pendingAckQueue, ref ackedQueue, ref acks, acked_packets, rtt, MaximumSequence); if (acks.Count == 33) { Debug.Log("process ack (1) ok"); } ; if (acked_packets == 33) { Debug.Log("process ack (1) ok"); } ; if (ackedQueue.Count == 33) { Debug.Log("process ack (1) ok"); } ; if (pendingAckQueue.Count == 0) { Debug.Log("process ack (1) ok"); } ; ackedQueue.verify_sorted(MaximumSequence); for (int i = 0; i < acks.Count; ++i) { Debug.Log(acks[i]); } for (LinkedListNode <PacketData> node = ackedQueue.First; node != ackedQueue.Last.Next; node = node.Next) { Debug.Log(node.Value.sequence); } /////////////////////////////////////////////// print("check process ack (2)"); { PacketQueue pendingAckQueue2 = new PacketQueue(); for (uint i = 0; i < 33; ++i) { PacketData data = new PacketData(); data.sequence = i; data.time = 0.0f; pendingAckQueue2.insert_sorted(data, MaximumSequence); } pendingAckQueue2.verify_sorted(MaximumSequence); PacketQueue ackedQueue2 = new PacketQueue(); List <uint> acks2 = new List <uint>(); float rtt2 = 0.0f; uint acked_packets2 = 0; ReliabilitySystem.process_ack(32, 0x0000FFFF, ref pendingAckQueue2, ref ackedQueue2, ref acks2, acked_packets2, rtt2, MaximumSequence); if (acks2.Count == 17) { Debug.Log("process ack (2) ok"); } ; if (acked_packets2 == 17) { Debug.Log("process ack (2) ok"); } ; if (ackedQueue2.Count == 17) { Debug.Log("process ack (2) ok"); } ; if (pendingAckQueue2.Count == 33 - 17) { Debug.Log("process ack (2) ok"); } ; ackedQueue2.verify_sorted(MaximumSequence); for (LinkedListNode <PacketData> node = pendingAckQueue2.First; node != pendingAckQueue2.Last.Next; node = node.Next) { Debug.Log(node.Value.sequence); } print("==========================="); for (LinkedListNode <PacketData> node = ackedQueue2.First; node != ackedQueue2.Last.Next; node = node.Next) { Debug.Log(node.Value.sequence); } for (int i = 0; i < acks2.Count; ++i) { if (acks2[i] == i + 16) { Debug.Log("process ack (2) ok"); } ; } } ////////////////////////////////////////////// print("check process ack (3)\n"); { PacketQueue pendingAckQueue3 = new PacketQueue(); for (uint i = 0; i < 32; ++i) { PacketData data = new PacketData(); data.sequence = i; data.time = 0.0f; pendingAckQueue3.insert_sorted(data, MaximumSequence); } pendingAckQueue3.verify_sorted(MaximumSequence); PacketQueue ackedQueue3 = new PacketQueue(); List <uint> acks3 = new List <uint>(); float rtt3 = 0.0f; uint acked_packets3 = 0; ReliabilitySystem.process_ack(48, 0xFFFF0000, ref pendingAckQueue3, ref ackedQueue3, ref acks3, acked_packets3, rtt3, MaximumSequence); if (acks3.Count == 16) { Debug.Log("process ack(3) ok"); } ; if (acked_packets3 == 16) { Debug.Log("process ack(3) ok"); } ; if (ackedQueue3.Count == 16) { Debug.Log("process ack(3) ok"); } ; if (pendingAckQueue3.Count == 16) { Debug.Log("process ack(3) ok"); } ; ackedQueue3.verify_sorted(MaximumSequence); for (LinkedListNode <PacketData> node = pendingAckQueue3.First; node != pendingAckQueue3.Last.Next; node = node.Next) { Debug.Log(node.Value.sequence); } print("==========================="); for (LinkedListNode <PacketData> node = ackedQueue3.First; node != ackedQueue3.Last.Next; node = node.Next) { Debug.Log(node.Value.sequence); } for (int i = 0; i < acks3.Count; ++i) { if (acks3[i] == i + 16) { Debug.Log("process ack (3) ok"); } ; } } }
private static bool Prefix(ValveBase __instance, float dt) { //Debug.Log(" === ValveBase.ConduitUpdate(" + dt + ") Prefix " + __instance.conduitType); if (__instance.conduitType != (ConduitType)100 && __instance.conduitType != (ConduitType)101) { return(true); } FieldInfo fi1 = AccessTools.Field(typeof(ValveBase), "inputCell"); FieldInfo fi2 = AccessTools.Field(typeof(ValveBase), "outputCell"); FieldInfo fi3 = AccessTools.Field(typeof(ValveBase), "flowAccumulator"); ConduitFlow flowManager = null; //Debug.Log("ConduitUpdate " + dt); if (__instance.conduitType == (ConduitType)100) { flowManager = Conduit.GetFlowManager(ConduitType.Liquid); } else if (__instance.conduitType == (ConduitType)101) { flowManager = Conduit.GetFlowManager(ConduitType.Gas); } ConduitFlow.Conduit conduit = flowManager.GetConduit((int)fi1.GetValue(__instance)); if (!flowManager.HasConduit((int)fi1.GetValue(__instance)) || !flowManager.HasConduit((int)fi2.GetValue(__instance))) { __instance.UpdateAnim(); } if ((int)fi1.GetValue(__instance) > 0 && flowManager.HasConduit((int)fi1.GetValue(__instance)) && ((int)fi2.GetValue(__instance) > 0 && !flowManager.HasConduit((int)fi2.GetValue(__instance)))) { ConduitFlow.ConduitContents contents = conduit.GetContents(flowManager); //float num = Mathf.Min(contents.mass, this.currentFlow * dt); FieldInfo fi = AccessTools.Field(typeof(ValveBase), "currentFlow"); //float num = Mathf.Min(contents.mass, (float)fi.GetValue(this) * dt); float num = Mathf.Min(contents.mass, 10f * dt); //Debug.Log("ConduitUpdate " + num); if (num > 0f) { float num2 = num / contents.mass; int disease_count = (int)(num2 * (float)contents.diseaseCount); //Debug.Log("List " + num); if (__instance.conduitType == (ConduitType)100) { LiquidWarpData.LiquidPackets.Add(new PacketData((int)__instance.conduitType, (float)fi.GetValue(__instance), (int)fi2.GetValue(__instance), contents.element, num, contents.temperature, contents.diseaseIdx, disease_count)); } else if (__instance.conduitType == (ConduitType)101) { GasWarpData.GasPackets.Add(new PacketData((int)__instance.conduitType, (float)fi.GetValue(__instance), (int)fi2.GetValue(__instance), contents.element, num, contents.temperature, contents.diseaseIdx, disease_count)); } //float num3 = flowManager.AddElement(this.outputCell, contents.element, num, contents.temperature, contents.diseaseIdx, disease_count); //Game.Instance.accumulators.Accumulate(this.flowAccumulator, num3); //float num3 = Mathf.Min(num, 10f - contents.mass); float num3 = num; if (num3 > 0f) { flowManager.RemoveElement((int)fi1.GetValue(__instance), num3); } } __instance.UpdateAnim(); return(false); } if ((int)fi2.GetValue(__instance) > 0 && flowManager.HasConduit((int)fi2.GetValue(__instance))) { ConduitFlow.Conduit conduitO = flowManager.GetConduit((int)fi2.GetValue(__instance)); FieldInfo fi = AccessTools.Field(typeof(ValveBase), "currentFlow"); PacketData toRemove = null; foreach (PacketData packet in LiquidWarpData.LiquidPackets) { //Debug.Log("currentFlow = " + (float)fi.GetValue(__instance) + ", packet.currentFlow = " + packet.current_flow); if ((float)fi.GetValue(__instance) == packet.current_flow && (int)__instance.conduitType == packet.content_type) { float num3 = flowManager.AddElement((int)fi2.GetValue(__instance), packet.element, packet.mass, packet.temperature, packet.disease_idx, packet.disease_count); //Debug.Log("Adding Element to pipe: " + packet.mass + "," + num3); Game.Instance.accumulators.Accumulate((HandleVector <int> .Handle)fi3.GetValue(__instance), num3); toRemove = packet; break; } } if (toRemove != null) { LiquidWarpData.LiquidPackets.Remove(toRemove); toRemove = null; } foreach (PacketData packet in GasWarpData.GasPackets) { //Debug.Log("currentFlow = " + (float)fi.GetValue(__instance) + ", packet.currentFlow = " + packet.current_flow); if ((float)fi.GetValue(__instance) == packet.current_flow && (int)__instance.conduitType == packet.content_type) { float num3 = flowManager.AddElement((int)fi2.GetValue(__instance), packet.element, packet.mass, packet.temperature, packet.disease_idx, packet.disease_count); //Debug.Log("Adding Element to pipe: " + packet.mass + "," + num3); Game.Instance.accumulators.Accumulate((HandleVector <int> .Handle)fi3.GetValue(__instance), num3); toRemove = packet; break; } } if (toRemove != null) { GasWarpData.GasPackets.Remove(toRemove); toRemove = null; } __instance.UpdateAnim(); return(false); } return(false); }
internal override void Apply(PacketData packetData, float[] residue) { var data = packetData as PacketData1; if (data == null) throw new InvalidDataException("Incorrect packet data!"); if (data.Posts != null) { var stepFlags = UnwrapPosts(data); var n = data.BlockSize / 2; var lx = 0; var ly = data.Posts[0] * _multiplier; for (int i = 1; i < data.PostCount; i++) { var idx = _sortIdx[i]; if (stepFlags[idx]) { var hx = _xList[idx]; var hy = data.Posts[idx] * _multiplier; if (lx < n) RenderLineMulti(lx, ly, Math.Min(hx, n), hy, residue); lx = hx; ly = hy; } if (lx >= n) break; } ACache.Return(ref stepFlags); if (lx < n) { RenderLineMulti(lx, ly, n, ly, residue); } ACache.Return(ref data.Posts); } }
public void Handoff(string deviceID, Handler handler, PacketData packetData, params Value[] parameterArray) { ValidateParameterArray(parameterArray); Module module = Controller.GetHandlerOwner(handler.GetType()); module.AcceptHandoff(deviceID, handler.Name, packetData, parameterArray); }
private void buttonSendDataToServer_Click(object sender, EventArgs e) { PacketData xdata = new PacketData(); /****************************************************************/ //prepair the start packet xdata.Packet_Type = (ushort)PacketTypes.Message; xdata.Data_Type = (ushort)PacketTypesSubMessage.Start; xdata.Packet_Size = 16; xdata.maskTo = 0; xdata.idTo = 0; xdata.idFrom = 0; //Before we send the text, lets stuff those Number values in the first data packet! int num1 = 0; int.TryParse(textBoxNum1.Text, out num1); xdata.Data16 = num1; int num2 = 0; int.TryParse(textBoxNum2.Text, out num2); xdata.Data17 = num2; int pos = 0; int chunkSize = xdata.szStringDataA.Length; //300 bytes if (textBoxText.Text.Length <= xdata.szStringDataA.Length) { textBoxText.Text.CopyTo(0, xdata.szStringDataA, 0, textBoxText.Text.Length); chunkSize = textBoxText.Text.Length; } else { textBoxText.Text.CopyTo(0, xdata.szStringDataA, 0, xdata.szStringDataA.Length); } xdata.Data1 = (uint)chunkSize; byte[] byData = PacketFunctions.StructureToByteArray(xdata); SendMessageToServer(byData); /**************************************************/ //Send the message body(if there is any) xdata.Data_Type = (ushort)PacketTypesSubMessage.Guts; pos = chunkSize; //set position while (true) { int PosFromEnd = textBoxText.Text.Length - pos; if (PosFromEnd <= 0) { break; } Array.Clear(xdata.szStringDataA, 0, xdata.szStringDataA.Length); //Clear this field before putting more data in it if (PosFromEnd < xdata.szStringDataA.Length) { chunkSize = textBoxText.Text.Length - pos; } else { chunkSize = xdata.szStringDataA.Length; } textBoxText.Text.CopyTo(pos, xdata.szStringDataA, 0, chunkSize); xdata.Data1 = (uint)chunkSize; pos += chunkSize; //set new position byData = PacketFunctions.StructureToByteArray(xdata); SendMessageToServer(byData); } /**************************************************/ //Send an EndMessage xdata.Data_Type = (ushort)PacketTypesSubMessage.End; xdata.Data1 = (uint)pos; //send the total which should be the 'pos' value byData = PacketFunctions.StructureToByteArray(xdata); SendMessageToServer(byData); }
internal void PushBuffer(byte[] buffer, int read) { Debug.Assert(!_snapshotInBuffs.Any(b => object.ReferenceEquals(b, buffer))); PacketData packetData = new PacketData(); packetData.Buffer = buffer; packetData.Read = read; #if DEBUG packetData.Stack = _stateObj._lastStack; #endif _snapshotInBuffs.Add(packetData); }
/// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public void PushSend(PacketData data) { PushSend(data.ToByte()); }
public ICollection <Packet> ReadLog(Stream stream, ProgressCallback callback) { Type[] constrType = new Type[] { typeof(int) }; object[] param = new object[1]; Assembly asm = typeof(Packet).Assembly; List <Packet> packets = new List <Packet>(); ArrayList ignored = new ArrayList(); Hashtable pakByName = new Hashtable(512); int counter = 0; using (BinaryReader s = new BinaryReader(stream, Encoding.ASCII)) { if (callback != null) { callback(0, (int)stream.Length); } string header = s.ReadString(); if (header != "[PacketLogConverter v1]") { throw new Exception("Wrong log format: " + header); } while (stream.Position < stream.Length) { if (callback != null && (counter++ & 0xFFF) == 0) // update progress every 4k packets { callback((int)(stream.Position >> 10), (int)(stream.Length >> 10)); } Packet p; int size = s.ReadUInt16(); string typeName = s.ReadString(); try { PacketData d = (PacketData)pakByName[typeName]; if (d == null) { Type t = asm.GetType(typeName); d = new PacketData(); d.constructor = t.GetConstructor(constrType); d.attr = PacketManager.GetPacketTypeAttribute(t); pakByName[typeName] = d; } param[0] = size; p = (Packet)d.constructor.Invoke(param); p.Attribute = d.attr; } catch (Exception e) { Log.Error("instantiate: " + typeName, e); ignored.Add(typeName + ": " + e.Message); stream.Position += size + 12; continue; } p.Code = (byte)s.ReadUInt16(); // 2 bytes p.Direction = (ePacketDirection)s.ReadByte(); // 1 byte p.Protocol = (ePacketProtocol)s.ReadByte(); // 1 byte p.Time = new TimeSpan(s.ReadInt64()); // 8 bytes p.Write(s.ReadBytes(size), 0, size); p.AllowClassChange = false; packets.Add(p); } if (ignored.Count > 0) { StringBuilder str = new StringBuilder("Ignored packets (count " + ignored.Count.ToString() + "):\n\n"); for (int i = 0;; i++) { str.Append(ignored[i]).Append('\n'); if (i > 16) { str.Append("...\n"); str.Append("and ").Append(ignored.Count - i + 1).Append(" more."); break; } } Log.Info(str.ToString()); } return(packets); } }
private IEnumerator QueryServerCoroutine(string hostname, int port) { using (var client = new NetworkClient()) { var connectTask = new Task(() => { client.Connect(hostname, port); }); connectTask.Start(); // wait until server is connected while (!connectTask.IsCompleted) { yield return(null); } // make sure connection is successful if (connectTask.IsFaulted) { if (connectTask.IsFaulted || !client.Connected) { throw connectTask.Exception; } } // create handshake to send to server Packet[] handshakePackets = new Packet[] { new HandshakePacket() { Address = hostname, Port = port, NextState = NetworkClient.ProtocolState.STATUS }, new RequestPacket() }; ServerStatus status = new ServerStatus(); var retreiveStatusTask = new Task(() => { // write handshake packets to server client.WritePackets(handshakePackets); // get server data ResponsePacket responsePacket; while (true) { PacketData responsePacketData = client.ReadNextPacket(); // check if it's a response packet if (responsePacketData.ID == 0x00) { responsePacket = new ResponsePacket(responsePacketData); break; } } // send ping var sw = new Stopwatch(); sw.Start(); client.WritePacket(new PingPongPacket()); // wait for pong packet while (true) { if (client.ReadNextPacket().ID == 0x01) { break; } } sw.Stop(); // set server status so the task can end status = new ServerStatus() { Packet = responsePacket, PingTime = (int)sw.ElapsedMilliseconds }; }); retreiveStatusTask.Start(); while (!retreiveStatusTask.IsCompleted) { yield return(null); } if (retreiveStatusTask.IsFaulted) { throw retreiveStatusTask.Exception; } Debug.Log($"Response: {status.Packet.JSONResponse}\nPing: {status.PingTime}ms"); } }
public static void saveAlertPacketContentToDb(PacketData data) { string rtu = data.moduleID; string tableName = MonitorOPCServer.getInstance().alertTable; if (tableName == null) return; string sql = string.Format("insert into [{0}]" + "(rtu,[time],alertPosition,alertValue) values('{1}','{2}',{3},{4}", tableName, data.moduleID, data.sendTime, data.alertPos, data.alertValue); DBUtil db = new DBUtil(); db.executeNonQuerySQL(sql); }
/// <summary> /// Send to server. /// </summary> /// <param name="packetData">The <see cref="PacketData"/>.</param> public void Send(PacketData packetData) { appNetworking.Send(packetData); }
void test_packet_queue() { uint MaximumSequence = 255; PacketQueue packetQueue = new PacketQueue(); PacketData data; print("check insert back"); for (uint i = 0; i < 100; ++i) { data = new PacketData(); data.sequence = i; packetQueue.insert_sorted(data, MaximumSequence); if (i > 1) { packetQueue.verify_sorted(MaximumSequence); } } print("check insert front"); packetQueue.Clear(); for (uint i = 100; i < 0; ++i) { data = new PacketData(); data.sequence = i; packetQueue.insert_sorted(data, MaximumSequence); if (i > 1) { packetQueue.verify_sorted(MaximumSequence); } } print("check insert random"); packetQueue.Clear(); for (uint i = 100; i < 0; ++i) { data = new PacketData(); data.sequence = (uint)(UnityEngine.Random.value * 10) & 0xff; packetQueue.insert_sorted(data, MaximumSequence); if (i > 1) { packetQueue.verify_sorted(MaximumSequence); } } print("check insert wrap around"); packetQueue.Clear(); for (uint i = 200; i <= 255; ++i) { data = new PacketData(); data.sequence = i; packetQueue.insert_sorted(data, MaximumSequence); if (i > 201) { packetQueue.verify_sorted(MaximumSequence); } } for (uint i = 0; i <= 50; ++i) { data = new PacketData(); data.sequence = i; packetQueue.insert_sorted(data, MaximumSequence); if (i > 1) { packetQueue.verify_sorted(MaximumSequence); } } }
public void Handoff(string deviceID, Type type, PacketData packetData, params Value[] parameterArray) { Handoff(deviceID, Controller.GetHeaderOwner(type), packetData, parameterArray); }
void AssembleMessage(String _ClientID, Byte[] _Data) { try { PacketData IncomingData = new PacketData(); IncomingData = (PacketData)PacketFunctions.ByteArrayToStructure(_Data, typeof(PacketData)); if (IncomingData.Verify() == false) { return; } switch (IncomingData.Packet_SubType) { case (UInt16)PacketTypeSubmessage.SUBMSG_MessageStart: { if (_WorkerSockets.ContainsKey(_ClientID)) { _WorkerSockets[_ClientID].MessageBuilder = new List <byte>(IncomingData.Data); } } break; case (UInt16)PacketTypeSubmessage.SUBMSG_MessageBody: { _WorkerSockets[_ClientID].MessageBuilder.AddRange(IncomingData.Data); } break; case (UInt16)PacketTypeSubmessage.SUBMSG_MessageEnd: { _WorkerSockets[_ClientID].MessageBuilder.AddRange(IncomingData.Data); var _UncompressedData = Helpers.DataCompressor.Unzip(_WorkerSockets[_ClientID].MessageBuilder.ToArray()); var _JObj = JObject.Parse(_UncompressedData); if (_FinalizedMessages.ContainsKey(_ClientID)) { _FinalizedMessages[_ClientID].Add(_JObj); } else { _FinalizedMessages.Add(_ClientID, new List <JObject>() { _JObj }); } _WorkerSockets[_ClientID].MessageBuilder = new List <byte>(); PacketData _Responce = new PacketData(); _Responce.Packet_Type = (UInt16)PacketType.TYPE_MessageReceived; Helpers.DataCompressor.Zip((String)_JObj["id"]).CopyTo(_Responce.Data, 0); //_FinalizedMessages Byte[] _ResponceData = PacketFunctions.StructureToByteArray(_Responce); SendMessage(_ClientID, _ResponceData, PacketType.TYPE_MessageReceived); } break; } } catch { // ToDo } }
internal override void Apply(PacketData packetData, float[] residue) { var data = packetData as PacketData0; if (data == null) throw new ArgumentException("Incorrect packet data!"); if (data.Amp > 0f) { // now we have the black art of high-end math... (this version is slow!) var barkMap = _barkMaps[data.BlockSize]; for (int i = 0; i < data.BlockSize; ) { var w = Math.PI * barkMap[i] / _bark_map_size; float multiplierP, multiplierQ; int orderAdjP, orderAdjQ; if (_order % 2 == 1) { // odd multiplierP = (float)(1.0 - Math.Pow(Math.Cos(w), 2)); orderAdjP = 3; multiplierQ = .25f; orderAdjQ = 1; } else { // even multiplierP = (float)(1.0 - Math.Cos(w)); orderAdjP = 2; multiplierQ = (float)(1.0 + Math.Cos(w)); orderAdjQ = 2; } // now down to business... var p = multiplierP * (_order - orderAdjP) / ( (4 * Math.Pow(Math.Cos(data.Coeff[1]) - Math.Cos(w), 2)) * (4 * Math.Pow(Math.Cos(data.Coeff[3]) - Math.Cos(w), 2)) * (4 * Math.Pow(Math.Cos(data.Coeff[5]) - Math.Cos(w), 2)) ); var q = multiplierQ * (_order - orderAdjQ) / ( (4 * Math.Pow(Math.Cos(data.Coeff[0]) - Math.Cos(w), 2)) * (4 * Math.Pow(Math.Cos(data.Coeff[2]) - Math.Cos(w), 2)) * (4 * Math.Pow(Math.Cos(data.Coeff[4]) - Math.Cos(w), 2)) ); // finally, get the linear value var value = (float)Math.Exp( .11512925 * ( (data.Amp * _ampOfs) / ( ((1 << _ampBits) - 1) * Math.Sqrt(p + q) ) - _ampOfs ) ); while (true) { var iteration_condition = barkMap[i]; residue[i] *= value; i++; if (barkMap[i] != iteration_condition) break; } } } }
/// <summary> /// Create a packet using a <see cref="PacketData"/> object /// </summary> /// <param name="data"></param> protected Packet(PacketData data) { PacketID = data.ID; Payload = data.Payload; }
internal abstract void Apply(PacketData packetData, float[] residue);
void Awake() { DontDestroyOnLoad(gameObject); clientNetworker = new Networker_Client_Unity(); clientNetworker.Setup("Forts"); clientNetworker.OnReceive("D_Instantiate", received => { PacketData <InstantiationPacket> data = new PacketData <InstantiationPacket>(received); if (data.packet.item_net_id != -1) { SpawnLocalCopyOfObject(data.playerId, data.packet.obj_name, data.packet.item_net_id, new Vector3(data.packet.x, data.packet.y, data.packet.z), new Vector3(data.packet.rotX, data.packet.rotY, data.packet.rotZ)); } return(false); }); clientNetworker.OnReceive("D_PositionRotation", received => { PacketData <PositionRotation> data = new PacketData <PositionRotation>(received); if (clientNetworker.GetPlayerID() != data.playerId) { GameObject go = FindSpawnedNetObject(data.packet.item_net_id); if (go != null) { if (data.packet.isRotation) { go.transform.rotation = Quaternion.Euler(data.packet.x, data.packet.y, data.packet.z); } else { go.transform.position = new Vector3(data.packet.x, data.packet.y, data.packet.z); } } } return(false); }); clientNetworker.OnReceive("D_Delete", received => { PacketData <DeletePacket> data = new PacketData <DeletePacket>(received); GameObject toDelete = null; foreach (GameObject go in identifier.currentAliveNetworkedObjects) { if (go != null && go.GetComponent <ScapeNet_Network_ID>().object_id == data.packet.item_net_id) { toDelete = go; break; } } identifier.currentAliveNetworkedObjects.Remove(toDelete); Destroy(toDelete); return(false); }); identifier = GetComponent <ScapeNet_Identifier>(); }
public static void savePacketContentToDb(PacketData data) { string rtu = data.moduleID; if ( !MonitorOPCServer.getInstance().dbNameMapping.ContainsKey(rtu)) { return; } string tableName = MonitorOPCServer.getInstance().dbNameMapping[rtu]; string sql = string.Format("insert into [{0}]" + "(rtu,[time],dbm,ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15,ch16,ch17,ch18) values" + "('{1}','{2}',{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21})", tableName, data.moduleID, data.sendTime, data.packetDataMap["GPRS-Level"], data.packetDataMap["AI1/AC1"], data.packetDataMap["AI2/AC2"] , data.packetDataMap["AI3/AC3"], data.packetDataMap["AI4/AC4"], data.packetDataMap["AI5/AC5"], data.packetDataMap["AI6/AC6"] , data.packetDataMap["DI1"], data.packetDataMap["DI2"], data.packetDataMap["DI3"], data.packetDataMap["DI4"] , data.packetDataMap["DI5"], data.packetDataMap["DI6"], data.packetDataMap["DO1"], data.packetDataMap["DO2"] , data.packetDataMap["DO3"], data.packetDataMap["DO4"], data.packetDataMap["DO5"], data.packetDataMap["DO6"]); DBUtil db = new DBUtil(); db.executeNonQuerySQL(sql); }
public void ReplyToHostCredentialRequest(byte[] message) { if (_client == null) { return; } Console.WriteLine($@"ReplyToHostCredentialRequest ThreadID = {Thread.CurrentThread.ManagedThreadId}"); var loc = 0; try { //We will assume to tell the host this is just an update of the //credentials we first sent during the application start. This //will be true if the 'message' argument is null, otherwise we //will change the packet type below to the 'TYPE_MyCredentials'. var paketType = (ushort)PacketTypes.CredentialsUpdate; if (message != null) { var myOldServerID = 0; //The host server has past my ID. var incomingData = (PacketData)PacketFunctions.ByteArrayToStructure(message, typeof(PacketData)); loc = 10; if (_myHostServerId > 0) { myOldServerID = _myHostServerId; } loc = 20; _myHostServerId = (int)incomingData.idTo; //Hang onto this value loc = 25; Console.WriteLine($@"My Host Server ID is {_myHostServerId}"); var myAddressAsSeenByTheHost = new string(incomingData.szStringDataA).TrimEnd('\0'); //My computer address SetSomeLabelInfoFromThread( $"My Address As Seen By The Server: {myAddressAsSeenByTheHost}, and my ID given by the server is: {_myHostServerId}"); _serverTime = incomingData.DataLong1; paketType = (ushort)PacketTypes.MyCredentials; } var xdata = new PacketData { Packet_Type = paketType, Data_Type = 0, Packet_Size = (ushort)Marshal.SizeOf(typeof(PacketData)), maskTo = 0, idTo = 0, idFrom = 0 }; //Station Name var p = Environment.MachineName; if (p.Length > (xdata.szStringDataA.Length - 1)) { p.CopyTo(0, xdata.szStringDataA, 0, (xdata.szStringDataA.Length - 1)); } else { p.CopyTo(0, xdata.szStringDataA, 0, p.Length); } xdata.szStringDataA[(xdata.szStringDataA.Length - 1)] = '\0'; //cap it off just incase //App and DLL Version var versionNumber = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor + "." + Assembly.GetEntryAssembly().GetName().Version.Build; loc = 30; versionNumber.CopyTo(0, xdata.szStringDataB, 0, versionNumber.Length); loc = 40; //Station Name var l = textBoxClientName.Text; if (l.Length > (xdata.szStringData150.Length - 1)) { l.CopyTo(0, xdata.szStringData150, 0, (xdata.szStringData150.Length - 1)); } else { l.CopyTo(0, xdata.szStringData150, 0, l.Length); } xdata.szStringData150[(xdata.szStringData150.Length - 1)] = '\0'; //cap it off just incase loc = 50; //Application type xdata.nAppLevel = (ushort)AppLevel.None; var byData = PacketFunctions.StructureToByteArray(xdata); loc = 60; SendMessageToServer(byData); loc = 70; } catch (Exception ex) { var exceptionMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; Console.WriteLine( $@"EXCEPTION at location {loc}, IN: ReplyToHostCredentialRequest - {exceptionMessage}"); } }
public ICollection<Packet> ReadLog(Stream stream, ProgressCallback callback) { Type[] constrType = new Type[] {typeof (int)}; object[] param = new object[1]; Assembly asm = typeof (Packet).Assembly; List<Packet> packets = new List<Packet>(); ArrayList ignored = new ArrayList(); Hashtable pakByName = new Hashtable(512); int counter = 0; using (BinaryReader s = new BinaryReader(stream, Encoding.ASCII)) { if (callback != null) callback(0, (int) stream.Length); string header = s.ReadString(); if (header != "[PacketLogConverter v1]") throw new Exception("Wrong log format: " + header); while (stream.Position < stream.Length) { if (callback != null && (counter++ & 0xFFF) == 0) // update progress every 4k packets callback((int)(stream.Position>>10), (int)(stream.Length>>10)); Packet p; int size = s.ReadUInt16(); string typeName = s.ReadString(); try { PacketData d = (PacketData) pakByName[typeName]; if (d == null) { Type t = asm.GetType(typeName); d = new PacketData(); d.constructor = t.GetConstructor(constrType); d.attr = PacketManager.GetPacketTypeAttribute(t); pakByName[typeName] = d; } param[0] = size; p = (Packet) d.constructor.Invoke(param); p.Attribute = d.attr; } catch (Exception e) { Log.Error("instantiate: " + typeName, e); ignored.Add(typeName + ": " + e.Message); stream.Position += size + 12; continue; } p.Code = (byte)s.ReadUInt16(); // 2 bytes p.Direction = (ePacketDirection) s.ReadByte(); // 1 byte p.Protocol = (ePacketProtocol) s.ReadByte(); // 1 byte p.Time = new TimeSpan(s.ReadInt64()); // 8 bytes p.Write(s.ReadBytes(size), 0, size); p.AllowClassChange = false; packets.Add(p); } if (ignored.Count > 0) { StringBuilder str = new StringBuilder("Ignored packets (count " + ignored.Count.ToString() + "):\n\n"); for (int i = 0;; i++) { str.Append(ignored[i]).Append('\n'); if (i > 16) { str.Append("...\n"); str.Append("and ").Append(ignored.Count - i + 1).Append(" more."); break; } } Log.Info(str.ToString()); } return packets; } }