public void Flush() { if (DataStream != null) { DataStream.Flush(); } }
/// <summary> /// Closes the stream. We used the close method to transfer /// the file via ftp. /// </summary> public void Close() { DataStream.WriteLine("]}"); DataStream.Flush(); DataStream.Close(); // transfer the file to the sftp service if (!HasUsers) { Logger.Debug("No Users to update. Skipping sftp process."); } else { var host = StreamConfig.Settings["host"]; var username = StreamConfig.Settings["username"]; var password = StreamConfig.Settings["password"]; var destinationPath = StreamConfig.Settings["destinationPath"]; SftpService.SendFile(FileName, host, username, password, destinationPath); } // clean up the temp file try { File.Delete(FileName); } catch (Exception ex) { Logger.Error(ex); throw; } }
public virtual void ProcessStream(SocketStateObject state, DataStream ds) { var goodPos = 0; while (true) { var id = 0U; var length = 0U; if (!ds.TryReadCompactUInt32(out id) || !ds.TryReadCompactUInt32(out length) || !ds.CanReadBytes((int)length)) { if (length > PacketSizeLimit) { Logger.Process("packetId = {0}, packetLength = {1}, packetSizeLimit = {2}", id, length, PacketSizeLimit); Stop(); } break; } var packetId = new PacketIdentifier(id, state.IsC2S ? PacketType.ClientPacket : PacketType.ServerPacket); var packetStream = new DataStream(ds.ReadBytes((int)length)); packetStream.IsLittleEndian = false; goodPos = ds.Position; ProcessPacketStream(state, packetId, packetStream); } ds.Position = goodPos; ds.Flush(); }
/// <summary> /// Send request to Sphinx server using underlying data stream and process server response. /// Connection behaviour is changed - underlying network connection will not closed until <see cref="PersistentTcpConnection.Close()"/> method is called or object is disposed. /// </summary> /// <param name="command">Command to execute</param> internal override void PerformCommand(CommandBase command) { ArgumentAssert.IsNotNull(command, "command"); if (!IsConnected) { Open(); } command.Serialize(DataStream); DataStream.Flush(); command.Deserialize(DataStream); }
public void Reset() { PolicyState = PacketPolicyState.Accept; State = PacketReaderState.WaitingId; PacketId = 0; PacketLength = 0; PacketStream.Clear(); if ((networkStream.Count >> 1) <= networkStream.Position) { networkStream.Flush(); } }
protected override void Dispose(bool disposing) { if (!disposing) { return; } DataStream.Flush(); if (OwnsStream) { DataStream.Dispose(); } }
/// <summary> /// Sends client protocol version and checks protocol version supported by server. /// Overriden version sends additional information to make connection persistent. /// </summary> protected override void SendHandshake() { base.SendHandshake(); // send ad-hoc 'persistent connection' command IBinaryWriter writer = FormatterFactory.CreateWriter(DataStream); _persistCommandInfo.Serialize(writer); // command body length writer.Write(sizeof(int)); // enable persistent connection boolean flag writer.Write(PERSIST_COMMAND_BODY); DataStream.Flush(); }
/// <summary> /// Send request to Sphinx server using underlying data stream and process server response. /// </summary> /// <param name="command">Command extending <see cref="CommandBase"/> class.</param> internal override void PerformCommand(CommandBase command) { ArgumentAssert.IsNotNull(command, "command"); Open(); try { SendHandshake(); command.Serialize(DataStream); DataStream.Flush(); command.Deserialize(DataStream); } finally { Close(); } }
public static void ReadLevelDifferences(bool deleteCurrent = false) { if (deleteCurrent && File.Exists("LevelDifferences.db")) { File.Delete("LevelDifferences.db"); } if (File.Exists("LevelDifferences.db")) { DataStream s = new DataStream(File.ReadAllBytes("LevelDifferences.db")); int length = s.ReadS32(); LevelDifferences = new List <LevelDifferenceInfo>(length); for (ushort i = 0; i < length; i++) { LevelDifferenceInfo info = new LevelDifferenceInfo { Difference = s.ReadS32(), ProgressFactor = s.ReadS32(), QualityFactor = s.ReadS32() }; LevelDifferences.Add(info); } s.Flush(); s.Close(); } else { var sheet = Game.GameData.GetSheet <CraftLevelDifference>(); int count = sheet.Count(); int[] keys = sheet.Keys.ToArray(); LevelDifferences = new List <LevelDifferenceInfo>(count); for (int i = 0; i < count; i++) { var value = sheet[keys[i]]; LevelDifferenceInfo info = new LevelDifferenceInfo { Difference = (short)value.Difference, ProgressFactor = (short)value.ProgressFactor, QualityFactor = (short)value.QualityFactor }; LevelDifferences.Add(info); } WriteLevelDifferences(); } }
/// <summary> /// Sends client protocol version and checks protocol version supported by server. /// </summary> /// <exception cref="SphinxException">Throws exception if server protocol version is not supported</exception> protected virtual void SendHandshake() { // check protocol version supported by remote Sphinx server IBinaryReader reader = FormatterFactory.CreateReader(DataStream); int protocolVersion = reader.ReadInt32(); if (protocolVersion < MAJOR_PROTOCOL_VERSION) { throw new SphinxException(String.Format(Messages.Exception_ProtocolVersionNotSupported, MAJOR_PROTOCOL_VERSION, protocolVersion)); } // send protocol version supported by client IBinaryWriter writer = FormatterFactory.CreateWriter(DataStream); writer.Write(MAJOR_PROTOCOL_VERSION); DataStream.Flush(); }
private static void WriteLevelDifferences() { DataStream s = new DataStream(); s.WriteS32(LevelDifferences.Count); for (int i = 0; i < LevelDifferences.Count; i++) { var value = LevelDifferences[i]; s.WriteS32(value.Difference); s.WriteS32(value.ProgressFactor); s.WriteS32(value.QualityFactor); } File.WriteAllBytes("LevelDifferences.db", s.GetBytes()); s.Flush(); s.Close(); }
/// <summary> /// ゴーストデータの記録 /// </summary> void SeveGhost() { FileInfo fi = new FileInfo(FilePathName); //ファイルインフォ StreamWriter DataStream; //ストリーム DataStream = fi.CreateText(); DataStream.Write(PlayerDataName + ","); //Playerデータの書き込み foreach (GhostCar.ReplayData rd in PlayerObject.replayData) { DataStream.Write(rd.fTime); DataStream.Write(','); DataStream.Write(rd.Position.x); DataStream.Write(','); DataStream.Write(rd.Position.y); DataStream.Write(','); DataStream.Write(rd.Position.z); DataStream.Write(','); DataStream.Write(rd.Rotate.x); DataStream.Write(','); DataStream.Write(rd.Rotate.y); DataStream.Write(','); DataStream.Write(rd.Rotate.z); DataStream.Write(','); DataStream.Write(rd.Rotate.w); DataStream.Write(','); } //UFODataの区切り DataStream.Write(UFODataName + ","); //UFOデータの書き込み foreach (GhostCar.ReplayData rd in PlayerUFOObject.replayData) { DataStream.Write(rd.fTime); DataStream.Write(','); DataStream.Write(rd.Position.x); DataStream.Write(','); DataStream.Write(rd.Position.y); DataStream.Write(','); DataStream.Write(rd.Position.z); DataStream.Write(','); DataStream.Write(rd.Rotate.x); DataStream.Write(','); DataStream.Write(rd.Rotate.y); DataStream.Write(','); DataStream.Write(rd.Rotate.z); DataStream.Write(','); DataStream.Write(rd.Rotate.w); DataStream.Write(','); } DataStream.Flush(); DataStream.Close(); }
public virtual void ProcessStream(SocketStateObject state, DataStream ds) { var goodPos = 0; while (true) { var id = 0U; var length = 0U; if (!ds.TryReadCompactUInt32(out id) || !ds.TryReadCompactUInt32(out length) || !ds.CanReadBytes((int)length)) { break; } var packetStream = new DataStream(ds.ReadBytes((int)length)); packetStream.IsLittleEndian = false; goodPos = ds.Position; ProcessPacketStream(state, id, packetStream); } ds.Position = goodPos; ds.Flush(); }
public static void WriteRecipeRotations() { DataStream s = new DataStream(); var keys = RecipeRotations.Keys.ToArray(); s.WriteS32(keys.Length); for (int i = 0; i < keys.Length; i++) { var value = keys[i]; s.WriteS32(value.Level); s.WriteS32(value.RequiredCraftsmanship); s.WriteS32(value.RequiredControl); s.WriteS32(value.Durability); s.WriteS32(value.MaxProgress); s.WriteS32(value.MaxQuality); var rotations = RecipeRotations[value]; s.WriteS32(rotations.Count); for (int j = 0; j < rotations.Count; j++) { s.WriteS32(rotations[j].MinLevel); s.WriteS32(rotations[j].MaxCraftsmanship); s.WriteS32(rotations[j].MinCraftsmanship); s.WriteS32(rotations[j].MinControl); s.WriteS32(rotations[j].CP); s.WriteS32(rotations[j].Rotation.Array.Length); for (int k = 0; k < rotations[j].Rotation.Array.Length; k++) { s.WriteU30(rotations[j].Rotation.Array[k]); } } } File.WriteAllBytes("RecipeRotations.db", s.GetBytes()); s.Flush(); s.Close(); }
public void Send(GameDataPacket packet, bool doRecord = true) { lock (senderLock) { DataStream.IsRecordEnabled = doRecord; Trace.TraceInformation("ServerGamer : Send {0}({1}) to client {2}", packet.GetType().Name, packet.GetHashCode(), this.GetHashCode()); Serializer.SerializeWithLengthPrefix <GameDataPacket>(DataStream, packet, PrefixStyle.Base128); DataStream.Flush(); } if (!DataStream.IsLastWriteSuccessful && !IsSpectator) { OnlineStatus = OnlineStatus.Offline; var handler = OnDisconnected; if (handler != null) { try { OnDisconnected(this); } catch (Exception) { } } } }
internal override void PerformCommand(CommandBase command) { ArgumentAssert.IsNotNull(command, "command"); Open(); try { if (!SkipHandshake) { base.SendHandshake(); } if (!SkipSerializeCommand) { command.Serialize(DataStream); } DataStream.Flush(); if (!SkipDeserializeCommand) { command.Deserialize(DataStream); } } finally { Close(); } }
static void Main(string[] args) { TcpClient HostSocket = new TcpClient(); NetworkStream DataStream; bool Active = true; while (true) { try { HostSocket.Connect(IPAddress.Parse("127.0.0.1"), 25565); break; } catch (Exception e) { Console.WriteLine(e.Message); } } SpeechSynthesizer synthesizer = new SpeechSynthesizer(); synthesizer.Volume = 100; // 0...100 synthesizer.Rate = 0; // -10...10 SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-UK")); Choices inputs = new Choices(); inputs.Add(new string[] { "Hello", "What are you?", "How are you?", "Good", "Bad", "Shutdown Interface", "Yes", "No", "Calculate" }); string[] Numbers = new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Hundred", "Thousand" }; GrammarBuilder gb = new GrammarBuilder(); gb.Append(inputs); Choices Nums = new Choices(); Nums.Add(Numbers); //gb.Append(Nums); Grammar G = new Grammar(gb); Grammar Dict = new DictationGrammar(); Dict.Weight = 0.4f; recognizer.LoadGrammarAsync(G); recognizer.LoadGrammarAsync(Dict); recognizer.SetInputToDefaultAudioDevice(); recognizer.SpeechRecognized += recognizer_SpeechRecognized; recognizer.RecognizeAsync(RecognizeMode.Multiple); synthesizer.SpeakAsync("Interface has been successfully initialised, greetings user!"); Console.WriteLine("Listening"); while (Active) { } void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { Console.WriteLine("VOICERECOGNIZED= " + e.Result.Text); if (e.Result.Text == "Shutdown Interface") { synthesizer.SpeakAsync("Are you sure?"); if (e.Result.Text == "Yes") { synthesizer.Speak("Shutting down interface, Goodbye"); Active = false; } else { synthesizer.Speak("Shutdown cancel"); } } else { Send(e.Result.Text); synthesizer.SpeakAsync(ListenAndWait()); } } void Send(string ToSend) { NetworkStream ServerStream = HostSocket.GetStream(); string data = ToSend; byte[] outStream = System.Text.Encoding.ASCII.GetBytes(data + "$END$"); ServerStream.Write(outStream, 0, outStream.Length); ServerStream.Flush(); } string ListenAndWait() { byte[] BytesReceived = new byte[2048]; string DataReceived = null; while (true) { try { DataStream = HostSocket.GetStream(); DataStream.Read(BytesReceived, 0, BytesReceived.Length); DataReceived = System.Text.Encoding.ASCII.GetString(BytesReceived); DataReceived = DataReceived.Substring(0, DataReceived.IndexOf("$END$")); break; } catch { } } return(DataReceived); } string Listen() { byte[] BytesReceived = new byte[2048]; string DataReceived = null; while (true) { try { DataStream = HostSocket.GetStream(); if (DataStream.DataAvailable) { DataStream.Read(BytesReceived, 0, BytesReceived.Length); DataReceived = System.Text.Encoding.ASCII.GetString(BytesReceived); DataReceived = DataReceived.Substring(0, DataReceived.IndexOf("$END$")); DataStream.Flush(); } else { DataReceived = ""; } break; } catch { DataReceived = ""; break; } } return(DataReceived); } }
public override void Flush() { DataStream.Flush(); }
private static void Update(UpdateOptions opts) { if (!File.Exists(opts.InputBin)) { Console.WriteLine("INPUT FILE NOT FOUND!!"); return; } if (!Directory.Exists(opts.InputDir)) { Console.WriteLine("INPUT DIRECTORY NOT FOUND!!"); return; } if (File.Exists(opts.Output)) { Console.WriteLine("OUTPUT FILE ALREADY EXISTS. IT WILL BE DELETED"); Console.Write("Continue (y/N)?"); string continueValue = Console.ReadLine(); if (string.IsNullOrEmpty(continueValue) || !string.Equals(continueValue, "y", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Cancelled by user."); return; } File.Delete(opts.Output); } string[] fileList; if (!string.IsNullOrEmpty(opts.FileList) && File.Exists(opts.FileList)) { Console.WriteLine($"Using \"{opts.FileList}\" as file list..."); fileList = File.ReadAllLines(opts.FileList); } else { fileList = Array.Empty <string>(); } Console.Write("Reading BIN file... "); Node binFile = NodeFactory.FromFile(opts.InputBin); (BinType binType, EndiannessMode endianness) = IdentifyFile(binFile); var readerParameters = new ReaderParameters { Endianness = endianness, FileNames = fileList, }; switch (binType) { case BinType.Standard: binFile.TransformWith <StandardBinReader, ReaderParameters>(readerParameters); break; case BinType.Dlc: binFile.TransformWith <DlcBinReader, ReaderParameters>(readerParameters); break; default: Console.WriteLine("Unknown file type"); return; } Console.WriteLine("DONE"); Console.Write($"Reading files in {opts.InputDir}... "); string[] newFiles = Directory.GetFiles(opts.InputDir, "*", SearchOption.AllDirectories); Parallel.ForEach(newFiles, newFile => { string file = Path.GetRelativePath(opts.InputDir, newFile).Replace('\\', '/'); Node oldNode = Navigator.SearchNode(binFile, file); if (oldNode == null) { Console.WriteLine($"{file} not found in {opts.InputBin}"); return; } DataStream s = DataStreamFactory.FromFile(newFile, FileOpenMode.Read); var type = oldNode.Tags["Type"]; switch (type) { case FileType.Normal: oldNode.ChangeFormat(new BinaryFormat(s), true); break; case FileType.Compressed: oldNode.ChangeFormat(new BinaryFormat(s), true); oldNode.Tags["InflatedSize"] = (uint)s.Length; oldNode.TransformWith <Compressor, EndiannessMode>(endianness); break; case FileType.CompressedAlternateEndian: oldNode.ChangeFormat(new BinaryFormat(s), true); oldNode.Tags["InflatedSize"] = (uint)s.Length; oldNode.TransformWith <Compressor, EndiannessMode>(endianness == EndiannessMode.BigEndian ? EndiannessMode.LittleEndian : EndiannessMode.BigEndian); break; } }); Console.WriteLine("DONE"); Console.Write("Building BIN archive... "); DataStream stream = DataStreamFactory.FromFile(opts.Output, FileOpenMode.Write); var parameters = new WriterParameters { Endianness = endianness, Stream = stream, }; var container = NodeFactory.CreateContainer("root"); int index = 0; foreach (Node srcNode in Navigator.IterateNodes(binFile)) { if (srcNode.IsContainer) { continue; } Node node = NodeFactory.FromSubstream(index.ToString(), srcNode.Stream, 0, srcNode.Stream.Length); foreach (string key in srcNode.Tags.Keys) { node.Tags[key] = srcNode.Tags[key]; } container.Add(node); index++; } container.SortChildren((x, y) => ((int)x.Tags["Index"]).CompareTo((int)y.Tags["Index"])); switch (binType) { case BinType.Standard: container.TransformWith <StandardBinWriter, WriterParameters>(parameters); break; case BinType.Dlc: container.TransformWith <DlcBinWriter, WriterParameters>(parameters); break; } stream.Flush(); stream.Dispose(); Console.WriteLine("DONE"); }
private static void Build(BuildOptions opts) { if (!Directory.Exists(opts.Input)) { Console.WriteLine("INPUT DIRECTORY NOT FOUND!!"); return; } if (File.Exists(opts.Output)) { Console.WriteLine("OUTPUT FILE ALREADY EXISTS. IT WILL BE DELETED"); Console.Write("Continue (y/N)?"); string continueValue = Console.ReadLine(); if (string.IsNullOrEmpty(continueValue) || !string.Equals(continueValue, "y", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Cancelled by user."); return; } File.Delete(opts.Output); } List <FileInfo> filesInfo = new (); if (!File.Exists(Path.Combine(opts.Input, "fileInfo.yaml"))) { Console.WriteLine("fileInfo.yaml not found. Using default values"); string[] files = Directory.GetFiles(opts.Input, "*"); filesInfo.AddRange(files.Select(file => new FileInfo { Name = Path.GetRelativePath(opts.Input, file), Type = FileType.Normal, })); } else { string info = Path.Combine(opts.Input, "fileInfo.yaml"); string yaml = File.ReadAllText(info); var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); filesInfo = deserializer.Deserialize <List <FileInfo> >(yaml); } Console.Write($"Reading files in {opts.Input}... "); var container = NodeFactory.CreateContainer("root"); for (int i = 0; i < filesInfo.Count; i++) { var fileInfo = filesInfo[i]; DataStream s = DataStreamFactory.FromFile(Path.Combine(opts.Input, fileInfo.Name), FileOpenMode.Read); Node node = NodeFactory.FromSubstream(i.ToString(), s, 0, s.Length); node.Tags["Type"] = fileInfo.Type; node.Tags["Index"] = fileInfo.Index; container.Add(node); } container.SortChildren((x, y) => ((int)x.Tags["Index"]).CompareTo((int)y.Tags["Index"])); Console.WriteLine("DONE"); DataStream stream = DataStreamFactory.FromFile(opts.Output, FileOpenMode.Write); var parameters = new WriterParameters { Endianness = opts.BigEndian ? EndiannessMode.BigEndian : EndiannessMode.LittleEndian, Stream = stream, }; Console.Write("Building BIN archive... "); if (opts.Dlc) { container.TransformWith <DlcBinWriter, WriterParameters>(parameters); } else { container.TransformWith <StandardBinCompressor, EndiannessMode>(parameters.Endianness) .TransformWith <StandardBinWriter, WriterParameters>(parameters); } stream.Flush(); stream.Dispose(); Console.WriteLine("DONE"); }
internal void HandleReceivedStream(DataStream ds) { while (true) { uint type; uint len; DataStream dataStream; if (!ds.TryReadCUInt32(out type)) { break; } if (!ds.TryReadCUInt32(out len)) { break; } if (!ds.CanRead((int)len)) { break; } dataStream = new DataStream(ds.ReadBytes((int)len)); dataStream.IsSwaped = true; InitializePacket(type, PacketType.ServerPacket, dataStream); if (type == 0x00) // Если это контейнер, то читаем из него данные { dataStream.Reset(); dataStream.IsSwaped = false; while (dataStream.CanRead()) { uint containerType; uint containerLen; DataStream containerDataStream; PacketType packetType; if (dataStream.ReadCUInt32() == 0x22) // type { dataStream.ReadCUInt32(); // buffer len containerLen = dataStream.ReadCUInt32() - 2; containerType = dataStream.ReadWord(); containerDataStream = new DataStream(dataStream.ReadBytes((int)containerLen)); packetType = PacketType.ServerContainer; } else { containerType = 0x45; containerDataStream = dataStream.ReadDataStream(); containerDataStream.IsSwaped = true; packetType = PacketType.ServerPacket; } InitializePacket(containerType, packetType, containerDataStream); } } ds.Flush(); } ds.Reset(); }
public static void ReadRecipeRotations(bool deleteCurrent = false) { if (deleteCurrent && File.Exists("RecipeRotations.db")) { File.Delete("RecipeRotations.db"); } if (File.Exists("RecipeRotations.db")) { DataStream s = new DataStream(File.ReadAllBytes("RecipeRotations.db")); int length = s.ReadS32(); RecipeRotations = new Dictionary <AbstractRecipeInfo, List <RecipeSolutionInfo> >(length); for (ushort i = 0; i < length; i++) { AbstractRecipeInfo info = new AbstractRecipeInfo { Level = s.ReadS32(), RequiredCraftsmanship = s.ReadS32(), RequiredControl = s.ReadS32(), Durability = s.ReadS32(), MaxProgress = s.ReadS32(), MaxQuality = s.ReadS32() }; var ll = s.ReadS32(); RecipeRotations[info] = new List <RecipeSolutionInfo>(ll); for (int j = 0; j < ll; j++) { RecipeSolutionInfo rotation = new RecipeSolutionInfo(); rotation.MinLevel = s.ReadS32(); rotation.MaxCraftsmanship = s.ReadS32(); rotation.MinCraftsmanship = s.ReadS32(); rotation.MinControl = s.ReadS32(); rotation.CP = s.ReadS32(); int l = s.ReadS32(); ushort[] array = new ushort[l]; for (int k = 0; k < l; k++) { array[k] = (ushort)s.ReadU30(); } rotation.Rotation = array; RecipeRotations[info].Add(rotation); } } s.Flush(); s.Close(); } else { RecipeRotations = new Dictionary <AbstractRecipeInfo, List <RecipeSolutionInfo> >(); var sheet = Game.GameData.GetSheet <Recipe>(); int count = sheet.Count; int[] keys = sheet.Keys.ToArray(); for (int i = 0; i < count; i++) { var value = sheet[keys[i]]; AbstractRecipeInfo abstractInfo = AbstractRecipeInfo.GetAbstractData(value); if (!RecipeRotations.ContainsKey(abstractInfo)) { RecipeRotations[abstractInfo] = new List <RecipeSolutionInfo>(); } } WriteRecipeRotations(); } }