public static void ParseData(List <byte> rawPacket, string ip, ushort port) { List <byte> data = rawPacket.GetRange(Packet.Reserved, rawPacket.Count - Packet.Reserved); PacketType type = (PacketType)rawPacket[0]; PacketValue value = (PacketValue)rawPacket[1]; byte id = rawPacket[2]; bool reliable = BitConverter.ToBoolean(rawPacket.ToArray(), 3); ushort packetId = BitConverter.ToUInt16(rawPacket.ToArray(), 4); long timeSend = BitConverter.ToInt64(rawPacket.ToArray(), 6); RecievedPacket recievedPacket = new RecievedPacket(data, id, type, value, ip, port, timeSend, packetId); // Check up if the packet was already recieved if (!CheckIfPacketWasAlreadyRecieved(id, packetId)) { // Queue the packet for processing RecievedPackets.Add(recievedPacket); QueuedPackets.Enqueue(recievedPacket); } // Send a confirmation back to the user if (reliable) { MultiplayerManager.sender.QueuePacket( new Packet(rawPacket.GetRange(4, 2), MultiplayerManager.LocalId, type, PacketValue.confirmation, ip, port) ); } }
public Packet(List <byte> data, byte peerId, PacketType type, PacketValue value, string ip, ushort port, bool reliable = false ) { this.type = type; this.value = value; this.peerId = peerId; this.ip = ip; this.port = port; this.packetId = CurrentPacketId; this.reliable = reliable; this.data.Add((byte)type); this.data.Add((byte)value); this.data.Add(peerId); this.data.Add(BitConverter.GetBytes(reliable)[0]); this.data.AddRange(BitConverter.GetBytes(CurrentPacketId)); this.data.AddRange(BitConverter.GetBytes(DateTimeOffset.Now.ToUnixTimeMilliseconds())); this.data.AddRange(data); CurrentPacketId++; }
async private void BtnGetFileInfo_Click(object sender, RoutedEventArgs e) { PacketValue packet = new PacketValue(protocol: Protocols.GET_FILE_LIST, value: 1); PacketSerialized result = await this.client.Send(packet).ConfigureAwait(false) as PacketSerialized; FileInfoCollection fileInfos = (FileInfoCollection)StreamUtil.DeserializeObject(result.SerializedData); UpdateGrid(fileInfos: fileInfos); }
static void Main(string[] args) { int count = 0; UdpListenerSimpleSync listener = new UdpListenerSimpleSync(SERVER_PORT); listener.Start(callback: (IPacket packet) => { PacketValue value = packet as PacketValue; Console.WriteLine($"receive: {value.Protocol}, {value.Value}"); return(new PacketValue(protocol: packet.Protocol, count++)); }); }
/// <summary> /// Send data to all the peers /// </summary> /// <param name="data"> byte data </param> /// <param name="type"> type of data </param> /// <param name="value"> value in the packet </param> /// <param name="sendReliable"> send this packet reliable </param> /// <param name="success"> only when reliable </param> /// <param name="fail"> only when reliable </param> public void SendDataToAllPeers( List <byte> data, PacketType type, PacketValue value, bool sendReliable = false, Action <PacketStatus> success = null, Action <PacketStatus> fail = null) { peerList.ExecStatement(peer => { if (peer != peerList.localInstance) { peer.SendData(data, type, value, sendReliable, success, fail); } }); }
// Send data to this peer public void SendData( List <byte> send, PacketType type, PacketValue value, bool sendReliable = false, Action <PacketStatus> success = null, Action <PacketStatus> fail = null ) { MultiplayerManager.sender.QueuePacket( new Packet(send, MultiplayerManager.peerManager.GetLocalPeer().id, type, value, ip, port, sendReliable), success, fail ); }
private bool TryGetPacketValue(ASMultiname multiname, ASClass @class, out PacketValue value) { ASMultiname returnValueType = multiname; if (@class != null) { returnValueType = GetTraitType(@class, multiname) ?? GetTraitType(@class.Instance, multiname); } switch (returnValueType.Name.ToLower()) { case "int": case "readint": case "gettimer": value = PacketValue.Integer; break; case "byte": case "readbyte": value = PacketValue.Byte; break; case "double": case "readdouble": value = PacketValue.Double; break; case "string": case "readstring": value = PacketValue.String; break; case "boolean": case "readboolean": value = PacketValue.Boolean; break; case "array": value = PacketValue.Unknown; break; default: { if (!IsOutgoing && !HGame.IsValidIdentifier(returnValueType.Name, true)) { value = PacketValue.Integer; // This reference call is most likely towards 'readInt' } else { value = PacketValue.Unknown; } break; } } return(value != PacketValue.Unknown); }
public RecievedPacket(List <byte> data, byte peerId, PacketType type, PacketValue value, string ip, ushort port, long timeSend, ushort packetId = 0 ) { this.type = type; this.value = value; this.peerId = peerId; this.ip = ip; this.port = port; this.timeSend = timeSend; this.packetId = packetId; this.data = data; destructionTime = 0; }
async static Task <IPacket> Receive(IPacket packet) { if (string.Equals(packet.Protocol, "0")) { PacketJson json = packet as PacketJson; Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(json.Json); string oldStageID = dic["OldStageID"]; string newStageID = dic["NewStageID"]; string userID = dic["UserID"]; Console.WriteLine($"[{json.Protocol}] oldStageID: {oldStageID}, newStageID: {newStageID}, userID: {userID}"); await listener.MoveStageAsync(oldStageID : oldStageID, newStageID : newStageID, userID : userID); return(null); } else if (string.Equals(packet.Protocol, "-1")) { PacketJson json = packet as PacketJson; Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(json.Json); string stageID = dic["StageID"]; string userID = dic["UserID"]; Console.WriteLine($"[{json.Protocol}] StageID: {stageID}, userID: {userID}"); await listener.DisconnectAsync(stageID : stageID, userID : userID); return(null); } else { PacketValue receive = packet as PacketValue; Console.WriteLine($"[{receive.Protocol}] {receive.Value}"); return(new PacketValue(protocol: receive.Protocol, value: receive.Value)); } }
static void Main(string[] args) { string ip = ClientIP; string msg; PacketValue receivePacket, sendPacket; PacketJson sendPacketJson; int stageID = 0; Task task1 = Task.Run(async() => { TcpClientConcurrencyAsync tcpClinet = new TcpClientConcurrencyAsync(serverIP: SERVER_IP, serverPort: SERVER_PORT, callback: async(IPacket packet) => { receivePacket = packet as PacketValue; Console.WriteLine($"[receive] {receivePacket.Protocol}: {receivePacket.Value}"); }); await tcpClinet.StartAsync(stageID: stageID.ToString(), userID: ip); Dictionary <string, string> dic; while (true) { msg = Console.ReadLine(); if (string.Equals(msg, "0")) { dic = new Dictionary <string, string>(); dic.Add("OldStageID", stageID++.ToString()); dic.Add("NewStageID", stageID.ToString()); dic.Add("UserID", ip); sendPacketJson = new PacketJson(protocol: msg, json: JsonConvert.SerializeObject(dic)); await tcpClinet.SendAsync(sendPacketJson); } else if (string.Equals(msg, "-1")) { dic = new Dictionary <string, string>(); dic.Add("StageID", stageID.ToString()); dic.Add("UserID", ip); sendPacketJson = new PacketJson(protocol: msg, json: JsonConvert.SerializeObject(dic)); await tcpClinet.SendAsync(sendPacketJson); } else { sendPacket = new PacketValue(protocol: ip, value: msg); await tcpClinet.SendAsync(sendPacket); } } }); task1.Wait(); //try //{ // TcpClientConcurrencySync tcpClinet = new TcpClientConcurrencySync(serverIP: SERVER_IP, serverPort: SERVER_PORT, callback: (IPacket packet) => // { // receivePacket = packet as PacketValue; // Console.WriteLine($"[receive] {receivePacket.Protocol}: {receivePacket.Value}"); // }); // tcpClinet.Start(stageID: stageID.ToString(), userID: ip); // Dictionary<string, string> dic; // while (true) // { // msg = Console.ReadLine(); // if (string.Equals(msg, "0")) // { // dic = new Dictionary<string, string>(); // dic.Add("OldStageID", stageID++.ToString()); // dic.Add("NewStageID", stageID.ToString()); // dic.Add("UserID", ip); // sendPacketJson = new PacketJson(protocol: msg, json: JsonConvert.SerializeObject(dic)); // tcpClinet.Send(sendPacketJson); // } // else if (string.Equals(msg, "-1")) // { // dic = new Dictionary<string, string>(); // dic.Add("StageID", stageID.ToString()); // dic.Add("UserID", ip); // sendPacketJson = new PacketJson(protocol: msg, json: JsonConvert.SerializeObject(dic)); // tcpClinet.Send(sendPacketJson); // } // else // { // sendPacket = new PacketValue(protocol: ip, value: msg); // tcpClinet.Send(sendPacket); // } // } //} //catch (Exception ex) //{ //} }
private PacketValue[] GetOutgoingStructure(ASCode code, ASInstruction beforeReturn, int length) { int getLocalEndIndex = -1; int pushingEndIndex = code.IndexOf(beforeReturn); PacketValue[] structure = new PacketValue[length]; Dictionary <int, int> pushedLocals = new Dictionary <int, int>(); for (int i = pushingEndIndex - 1; i >= 0; i--) { ASInstruction instruction = code[i]; if (instruction.OP == OPCode.GetProperty) { ASClass classToCheck = Class; GetPropertyIns getProperty = (GetPropertyIns)instruction; ASMultiname propertyName = getProperty.PropertyName; ASInstruction previous = code[i - 1]; if (previous.OP == OPCode.GetLex) { GetLexIns getLex = (GetLexIns)previous; classToCheck = classToCheck.GetABC().GetClass(getLex.TypeName); } if (!TryGetPacketValue(propertyName, classToCheck, out PacketValue piece)) { return(null); } structure[--length] = piece; } else if (Local.IsGetLocal(instruction.OP) && instruction.OP != OPCode.GetLocal_0) { Local local = (Local)instruction; pushedLocals.Add(local.Register, --length); if (getLocalEndIndex == -1) { getLocalEndIndex = i; } } if (length == 0) { break; } } for (int i = getLocalEndIndex - 1; i >= 0; i--) { ASInstruction instruction = code[i]; if (!Local.IsSetLocal(instruction.OP)) { continue; } Local local = (Local)instruction; if (pushedLocals.TryGetValue(local.Register, out int structIndex)) { ASInstruction beforeSet = code[i - 1]; pushedLocals.Remove(local.Register); switch (beforeSet.OP) { case OPCode.PushInt: case OPCode.PushByte: case OPCode.Convert_i: structure[structIndex] = PacketValue.Integer; break; case OPCode.Coerce_s: case OPCode.PushString: structure[structIndex] = PacketValue.String; break; case OPCode.PushTrue: case OPCode.PushFalse: structure[structIndex] = PacketValue.Boolean; break; default: throw new Exception($"Don't know what this value type is, tell someone about this please.\r\nOP: {beforeSet.OP}"); } } if (pushedLocals.Count == 0) { break; } } return(structure); }
private PacketValue[] GetOutgoingStructure(ASClass @class, ASMultiname propertyName) { ASMethod constructor = @class.Instance.Constructor; if (constructor.Body.Exceptions.Count > 0) { return(null); } ASCode code = constructor.Body.ParseCode(); if (code.JumpExits.Count > 0 || code.SwitchExits.Count > 0) { return(null); } List <PacketValue> structure = new List <PacketValue>(); for (int i = 0; i < code.Count; i++) { ASInstruction instruction = code[i]; if (instruction.OP == OPCode.NewArray) { NewArrayIns newArray = (NewArrayIns)instruction; if (newArray.ArgCount > 0) { PacketValue[] structurePieces = new PacketValue[newArray.ArgCount]; for (int j = i - 1, length = newArray.ArgCount; j >= 0; j--) { ASInstruction previous = code[j]; if (Local.IsGetLocal(previous.OP) && previous.OP != OPCode.GetLocal_0) { Local local = (Local)previous; ASParameter parameter = constructor.Parameters[local.Register - 1]; if (!TryGetPacketValue(parameter.Type, null, out PacketValue piece)) { return(null); } structurePieces[--length] = piece; } if (length == 0) { structure.AddRange(structurePieces); break; } } } } else if (instruction.OP == OPCode.ConstructSuper) { ConstructSuperIns constructSuper = (ConstructSuperIns)instruction; if (constructSuper.ArgCount > 0) { ASClass superClass = @class.GetABC().GetClass(@class.Instance.Super); structure.AddRange(GetOutgoingStructure(superClass, propertyName)); } } if (instruction.OP != OPCode.GetProperty) { continue; } GetPropertyIns getProperty = (GetPropertyIns)instruction; if (getProperty.PropertyName != propertyName) { continue; } ASInstruction next = code[++i]; ASClass classToCheck = @class; if (Local.IsGetLocal(next.OP)) { if (next.OP == OPCode.GetLocal_0) { continue; } Local local = (Local)next; ASParameter parameter = constructor.Parameters[local.Register - 1]; if (!TryGetPacketValue(parameter.Type, null, out PacketValue piece)) { return(null); } structure.Add(piece); } else { if (next.OP == OPCode.FindPropStrict) { classToCheck = null; } else if (next.OP == OPCode.GetLex) { GetLexIns getLex = (GetLexIns)next; classToCheck = classToCheck.GetABC().GetClass(getLex.TypeName); } do { next = code[++i]; propertyName = null; if (next.OP == OPCode.GetProperty) { getProperty = (GetPropertyIns)next; propertyName = getProperty.PropertyName; } else if (next.OP == OPCode.CallProperty) { CallPropertyIns callProperty = (CallPropertyIns)next; propertyName = callProperty.PropertyName; } }while (next.OP != OPCode.GetProperty && next.OP != OPCode.CallProperty); if (!TryGetPacketValue(propertyName, classToCheck, out PacketValue piece)) { return(null); } structure.Add(piece); } } return(structure.Count == 0 ? null : structure.ToArray()); }
async static Task <PacketSerialized> GetFileList(PacketValue packet) { FileInfoCollection files = await DatabaseManager.GetFileList(); return(new PacketSerialized(protocol: packet.Protocol, serializedData: StreamUtil.SerializeObject(files))); }
/// <summary> /// Logic that parses recieved packets from MindWave headset. /// </summary> private async void ParseHeadsetPackets() { int QualityBuffer = 0; try { while (true) { var resultArray = await NextBuffer(); int?indexOfUsefulDataHeader = HeaderIndex.Get(resultArray); if (indexOfUsefulDataHeader.HasValue == false) { // ignore data and just dump it } else { // PACKET PARSING BLOCK // Packet Check if (indexOfUsefulDataHeader.Value + PacketLenght > resultArray.Length) { var nextResultsArray = await NextBuffer(); resultArray = resultArray.Concat(nextResultsArray).ToArray(); } // Packet OK var PctData = resultArray.Skip(indexOfUsefulDataHeader.Value).Take(PacketLenght + 4).ToArray(); RaisePacketRecieved(); // Check out: // http://wearcam.org/ece516/mindset_communications_protocol.pdf RealtimeData = new MindsetDataStruct(PctData[4], //Signal Quality PacketValue.Get(PctData, 7, 9), //Delta PacketValue.Get(PctData, 10, 12), //Theta PacketValue.Get(PctData, 13, 15), //Low Alpha PacketValue.Get(PctData, 16, 18), //High Alpha PacketValue.Get(PctData, 19, 21), //Low Beta PacketValue.Get(PctData, 22, 24), //High Beta PacketValue.Get(PctData, 25, 27), //Low Gamma PacketValue.Get(PctData, 28, 30), //Mid Gamma PctData[32], //Attention PctData[34], //Meditation DateTime.Now //Timestamp of recieved data ); //Raising the quality change event (If necessary). if (RealtimeData.Quality != QualityBuffer) { RaiseQualityChange(RealtimeData.Quality.ToString()); } QualityBuffer = RealtimeData.Quality; //RECORDING BLOCK if (RecordingEnabled) { //Count packets while recording PacketNum++; //Number of "skipped" packets is matching or is grater than recording fidelity, so we want to record this packet. if (PacketNum >= RecordingFidelity) { //The filtering is enabled so record only good quality packets (Signal quality = 0 and eSense data > 0). if (RecordingFiltering && RealtimeData.Quality == 0 && RealtimeData.Meditation > 0 && RealtimeData.Attention > 0) { //Adding the packet to the recorded packet list. RecordedData.Add(RealtimeData); //The packet is recorded so we reset the counter. PacketNum = 0; } //The filtering is not enabled so we record every packet, even the bad quality ones. if (!RecordingFiltering) { RecordedData.Add(RealtimeData); PacketNum = 0; } } } } } } catch { RaiseParseFail(); } }