private static void PipesReader(string pipeName) { try { using (var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In)) { pipeReader.WaitForConnection(); WriteLine("reader connected"); const int BUFFERSIZE = 256; bool completed = false; while (!completed) { byte[] buffer = new byte[BUFFERSIZE]; int nRead = pipeReader.Read(buffer, 0, BUFFERSIZE); string line = Encoding.UTF8.GetString(buffer, 0, nRead); WriteLine(line); if (line == "bye") completed = true; } } WriteLine("completed reading"); ReadLine(); } catch (Exception ex) { WriteLine(ex.Message); } }
private async void StartInternal(CancellationToken cancellationToken) { byte[] buffer = new byte[256]; var commandBuilder = new StringBuilder(); var serverStream = new NamedPipeServerStream(this.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0); using (cancellationToken.Register(() => serverStream.Close())) { while (!cancellationToken.IsCancellationRequested) { await Task.Factory.FromAsync(serverStream.BeginWaitForConnection, serverStream.EndWaitForConnection, TaskCreationOptions.None); int read = await serverStream.ReadAsync(buffer, 0, buffer.Length); commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); while (!serverStream.IsMessageComplete) { read = serverStream.Read(buffer, 0, buffer.Length); commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); } var response = this.HandleReceivedCommand(commandBuilder.ToString()); var responseBytes = Encoding.ASCII.GetBytes(response); serverStream.Write(responseBytes, 0, responseBytes.Length); serverStream.WaitForPipeDrain(); serverStream.Disconnect(); commandBuilder.Clear(); } } }
static void Main() { using (var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.Out)) { try { Console.WriteLine("NamedPipeServerStream object created."); // Wait for a client to connect Console.Write("Waiting for client connection..."); pipeServer.WaitForConnection(); Console.WriteLine("Client connected."); // Read user input and send that to the client process. using (StreamWriter sw = new StreamWriter(pipeServer)) { sw.AutoFlush = true; while (true) { Console.Write("Enter text: "); sw.WriteLine(Console.ReadLine()); } } } catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } } }
public void Run() { while (true) { NamedPipeServerStream pipeStream = null; try { pipeStream = new NamedPipeServerStream(ConnectionName, PipeDirection.InOut, -1, PipeTransmissionMode.Message); pipeStream.WaitForConnection(); if (_stop) return; // Spawn a new thread for each request and continue waiting var t = new Thread(ProcessClientThread); t.Start(pipeStream); } catch (Exception) { if (pipeStream != null) pipeStream.Dispose(); throw; } } // ReSharper disable once FunctionNeverReturns }
public PipeLink(string spec) { this.pipe = new NamedPipeServerStream(spec, PipeDirection.InOut, 1, PipeTransmissionMode.Byte); Thread t = new Thread(this.Connect); t.Name = "Pipe Connector"; t.Start(); }
private void startServer(object state) { try { var pipe = state.ToString(); using (var server = new NamedPipeServerStream(pipe, PipeDirection.Out)) { server.WaitForConnection(); while (server.IsConnected) { if (_messages.Count == 0) { Thread.Sleep(100); continue; } var bytes = _messages.Pop(); var buffer = new byte[bytes.Length + 1]; Array.Copy(bytes, buffer, bytes.Length); buffer[buffer.Length - 1] = 0; server.Write(buffer, 0, buffer.Length); } } } catch { } }
/// <summary> /// Creates a Pipe to interact with an injected DLL or another program. /// </summary> public Pipe(Client client, string name) { this.client = client; this.name = name; pipe = new NamedPipeServerStream(name, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); pipe.BeginWaitForConnection(new AsyncCallback(BeginWaitForConnection), null); }
public Listener(StreamReader reader, NamedPipeServerStream server) { serverStream = server; SR = reader; thread = new Thread(new ThreadStart(Run)); thread.Start(); }
// Method ==================================================================================== public void Start(string name) { pipeName = name; isExitThread = false; Thread thread = new Thread(() => { while (true) { if (isExitThread == true) { isExitThread = false; break; } try { // xp 无法使用pipe,所以加点延迟预防一下... Thread.Sleep(500); NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); pipeServer.BeginWaitForConnection(ReadCallback, pipeServer); } catch (Exception ex) { Logger.WriteException(ex); } } }); thread.IsBackground = true; thread.Start(); }
public void Start() { try { ExtractUpdaterFromResource(); using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("gsupdater", PipeDirection.Out)) { ExecuteUpdater(); pipeServer.WaitForConnection(); using (StreamWriter sw = new StreamWriter(pipeServer)) { sw.AutoFlush = true; sw.WriteLine(_sourcePath); sw.WriteLine(_applicationPath); } Environment.Exit(0); } } catch (Exception e) { MessageBox.Show(@"Une erreur s'est produite lors du démarrage de la mise à jour de l'application" + Environment.NewLine + @"Detail du message :" + Environment.NewLine + e.Message); } }
private static async void StartGeneralServer() { Log.Info("Started server"); var exceptionCount = 0; while(exceptionCount < 10) { try { using(var pipe = new NamedPipeServerStream("hdtgeneral", PipeDirection.In, 1, PipeTransmissionMode.Message)) { Log.Info("Waiting for connecetion..."); await Task.Run(() => pipe.WaitForConnection()); using(var sr = new StreamReader(pipe)) { var line = sr.ReadLine(); switch(line) { case "sync": HearthStatsManager.SyncAsync(false, true); break; } Log.Info(line); } } } catch(Exception ex) { Log.Error(ex); exceptionCount++; } } Log.Info("Closed server. ExceptionCount=" + exceptionCount); }
private static async void StartImportServer() { Log.Info("Started server"); var exceptionCount = 0; while(exceptionCount < 10) { try { using(var pipe = new NamedPipeServerStream("hdtimport", PipeDirection.In, 1, PipeTransmissionMode.Message)) { Log.Info("Waiting for connecetion..."); await Task.Run(() => pipe.WaitForConnection()); using(var sr = new StreamReader(pipe)) { var line = sr.ReadLine(); var decks = JsonConvert.DeserializeObject<JsonDecksWrapper>(line); decks.SaveDecks(); Log.Info(line); } } } catch(Exception ex) { Log.Error(ex); exceptionCount++; } } Log.Info("Closed server. ExceptionCount=" + exceptionCount); }
static void IPCThread() { string pipeName = string.Format("bizhawk-pid-{0}-IPCKeyInput", System.Diagnostics.Process.GetCurrentProcess().Id); for (; ; ) { using (NamedPipeServerStream pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024)) { try { pipe.WaitForConnection(); BinaryReader br = new BinaryReader(pipe); for (; ; ) { int e = br.ReadInt32(); bool pressed = (e & 0x80000000) != 0; lock (PendingEventList) PendingEventList.Add(new KeyInput.KeyEvent { Key = (Key)(e & 0x7FFFFFFF), Pressed = pressed }); } } catch { } } } }
private void CreatePipeServer() { pipeServer = new NamedPipeServerStream("www.pmuniverse.net-installer", PipeDirection.InOut, 1, (PipeTransmissionMode)0, PipeOptions.Asynchronous); pipeServer.WaitForConnection(); //pipeServer.BeginWaitForConnection(new AsyncCallback(PipeConnected), pipeServer); Pipes.StreamString streamString = new Pipes.StreamString(pipeServer); while (pipeServer.IsConnected) { string line = streamString.ReadString(); if (!string.IsNullOrEmpty(line)) { if (line.StartsWith("[Status]")) { installPage.UpdateStatus(line.Substring("[Status]".Length)); } else if (line.StartsWith("[Progress]")) { installPage.UpdateProgress(line.Substring("[Progress]".Length).ToInt()); } else if (line.StartsWith("[Component]")) { installPage.UpdateCurrentComponent(line.Substring("[Component]".Length)); } else if (line == "[Error]") { throw new Exception(line.Substring("[Error]".Length)); } else if (line == "[InstallComplete]") { installPage.InstallComplete(); break; } } } pipeServer.Close(); }
static void ConnectPythonPipe(NamedPipeServerStream server) { Console.WriteLine("Waiting for connection to Python..."); server.WaitForConnection(); Console.WriteLine("Connected to Python."); }
/// <summary> /// Runs the bundle with the provided command-line. /// </summary> /// <param name="commandLine">Optional command-line to pass to the bundle.</param> /// <returns>Exit code from the bundle.</returns> public int Run(string commandLine = null) { WaitHandle[] waits = new WaitHandle[] { new ManualResetEvent(false), new ManualResetEvent(false) }; int returnCode = 0; int pid = Process.GetCurrentProcess().Id; string pipeName = String.Concat("bpe_", pid); string pipeSecret = Guid.NewGuid().ToString("N"); using (NamedPipeServerStream pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1)) { using (Process bundleProcess = new Process()) { bundleProcess.StartInfo.FileName = this.Path; bundleProcess.StartInfo.Arguments = String.Format("{0} -burn.embedded {1} {2} {3}", commandLine ?? String.Empty, pipeName, pipeSecret, pid); bundleProcess.StartInfo.UseShellExecute = false; bundleProcess.StartInfo.CreateNoWindow = true; bundleProcess.Start(); Connect(pipe, pipeSecret, pid, bundleProcess.Id); PumpMessages(pipe); bundleProcess.WaitForExit(); returnCode = bundleProcess.ExitCode; } } return returnCode; }
public PipeServer() { PipeName = string.Format("exTibiaS{0}", GameClient.Process.Id); Pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); OnReceive += new PipeListener(PipeServer_OnReceive); Pipe.BeginWaitForConnection(new AsyncCallback(BeginWaitForConnection), null); }
private void ListenForArguments(object state) { try { using (NamedPipeServerStream stream = new NamedPipeServerStream(this.identifier.ToString())) { using (StreamReader reader = new StreamReader(stream)) { stream.WaitForConnection(); List<string> list = new List<string>(); while (stream.IsConnected) { list.Add(reader.ReadLine()); } ThreadPool.QueueUserWorkItem(new WaitCallback(this.CallOnArgumentsReceived), list.ToArray()); } } } catch (IOException) { } finally { this.ListenForArguments(null); } }
private static void StartServer(Type interfaceType, Type implType, string pipeName) { //create the server var controller = new RpcController(); var server = new RpcServer(controller); //register the service with the server. We must specify the interface explicitly since we did not use attributes server.GetType() .GetMethod("RegisterService") .MakeGenericMethod(interfaceType) .Invoke(server, new[] {Activator.CreateInstance(implType)}); //build the connection using named pipes try { pipeServerStreamIn = CreateNamedPipe(pipeName + "ctos", PipeDirection.In); pipeServerStreamOut = CreateNamedPipe(pipeName + "stoc", PipeDirection.Out); streamsCreated = true; pipeServerStreamIn.WaitForConnection(); pipeServerStreamOut.WaitForConnection(); //create and start the channel which will receive requests var channel = new StreamRpcChannel(controller, pipeServerStreamIn, pipeServerStreamOut, useSharedMemory: true); channel.Start(); } catch (IOException e) { //swallow and exit Console.WriteLine("Something went wrong (pipes busy?), quitting: " + e); throw; } }
private void EnsurePipeInstance() { if (_stream == null) { var direction = PipeDirection.InOut; var maxconn = 254; var mode = PipeTransmissionMode.Byte; var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None; var inbuf = 4096; var outbuf = 4096; // TODO: security try { _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); } catch (NotImplementedException) // Mono still does not support async, fallback to sync { if (_asyncMode) { options &= (~PipeOptions.Asynchronous); _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); _asyncMode = false; } else { throw; } } } }
/// <summary> /// Listens for arguments on a named pipe. /// </summary> /// <param name="state">State object required by WaitCallback delegate.</param> private void ListenForArguments(Object state) { try { using (NamedPipeServerStream server = new NamedPipeServerStream(identifier.ToString())) using (StreamReader reader = new StreamReader(server)) { server.WaitForConnection(); List<String> arguments = new List<String>(); while (server.IsConnected) { string line = reader.ReadLine(); if (line != null && line.Length > 0) { arguments.Add(line); } } ThreadPool.QueueUserWorkItem(new WaitCallback(CallOnArgumentsReceived), arguments.ToArray()); } } catch (IOException) { } //Pipe was broken finally { ListenForArguments(null); } }
private static void PipesReader2(string pipeName) { try { var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In); using (var reader = new StreamReader(pipeReader)) { pipeReader.WaitForConnection(); WriteLine("reader connected"); bool completed = false; while (!completed) { string line = reader.ReadLine(); WriteLine(line); if (line == "bye") completed = true; } } WriteLine("completed reading"); ReadLine(); } catch (Exception ex) { WriteLine(ex.Message); } }
private void LaunchServer(string pipeName) { try { Console.WriteLine("Creating server: " + pipeName); server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 4); Console.WriteLine("Waiting for connection"); server.WaitForConnection(); reader = new StreamReader(server); Task.Factory.StartNew(() => { Console.WriteLine("Begin server read loop"); while (true) { try { var line = reader.ReadLine(); messages.Enqueue(line); } catch (Exception ex) { Console.WriteLine("ServerLoop exception: {0}", ex.Message); } } }); } catch (Exception ex) { Console.WriteLine("LaunchServer exception: {0}", ex.Message); } }
private void UserSignIn(string username, string password) { string hashed_password = sha256(password); MessageBox.Show(hashed_password); //send username and password to python and checks if correct string info = username + "#" + hashed_password; // Open the named pipe. var server = new NamedPipeServerStream("Communicate"); server.WaitForConnection(); var br = new BinaryReader(server); var bw = new BinaryWriter(server); send(bw, info); string message = recv(br); server.Close(); server.Dispose(); //if receives true then send the user to the next gui. if (message == "1") { SaveFile form = new SaveFile(); form.Show(); } else { MessageBox.Show("incorrect password or username"); this.Show(); } }
public ProxyProcessManager() { this.commandPipeName = String.Format(ProxyProcessManager.PIPE_NAME_FMT, Guid.NewGuid()); this.commandPipe = new NamedPipeServerStream(this.commandPipeName); this.commandPipeReader = new BinaryReader(this.commandPipe); this.commandPipeWriter = new BinaryWriter(this.commandPipe); }
public void Worker() { while (true) { try { var serverStream = new NamedPipeServerStream("YetAnotherRelogger", PipeDirection.InOut, 100, PipeTransmissionMode.Message, PipeOptions.Asynchronous); serverStream.WaitForConnection(); ThreadPool.QueueUserWorkItem(state => { using (var pipeClientConnection = (NamedPipeServerStream)state) { var handleClient = new HandleClient(pipeClientConnection); handleClient.Start(); } }, serverStream); } catch (Exception ex) { Logger.Instance.WriteGlobal(ex.Message); } Thread.Sleep(Program.Sleeptime); } }
static public async Task WaitForConnectionAsync(this System.IO.Pipes.NamedPipeServerStream self, CancellationToken token) { Exception err = null; var cts = new CancellationTokenSource(); Thread t = new Thread(delegate() { try { self.WaitForConnection(); } catch (Exception x) { err = x; cts.Cancel(); } }); try { await Task.Delay(-1, cts.Token); } catch (Exception) { } if (err != null) { throw new Exception(err.Message, err); } }
public async Task NamedPipeWriteViaAsyncFileStream(bool asyncWrites) { string name = Guid.NewGuid().ToString("N"); using (var server = new NamedPipeServerStream(name, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { Task serverTask = Task.Run(async () => { await server.WaitForConnectionAsync(); for (int i = 0; i < 6; i++) Assert.Equal(i, server.ReadByte()); }); WaitNamedPipeW(@"\\.\pipe\" + name, -1); using (SafeFileHandle clientHandle = CreateFileW(@"\\.\pipe\" + name, GENERIC_WRITE, FileShare.None, IntPtr.Zero, FileMode.Open, (int)PipeOptions.Asynchronous, IntPtr.Zero)) using (var client = new FileStream(clientHandle, FileAccess.Write, bufferSize: 3, isAsync: true)) { var data = new[] { new byte[] { 0, 1 }, new byte[] { 2, 3 }, new byte[] { 4, 5 } }; foreach (byte[] arr in data) { if (asyncWrites) await client.WriteAsync(arr, 0, arr.Length); else client.Write(arr, 0, arr.Length); } } await serverTask; } }
public MultiplexedPipeConnection(NamedPipeServerStream pipeServer, Microsoft.Samples.ServiceBus.Connections.QueueBufferedStream multiplexedOutputStream) : base(pipeServer.Write) { this.pipeServer = pipeServer; this.outputPump = new MultiplexConnectionOutputPump(pipeServer.Read, multiplexedOutputStream.Write, Id); this.outputPump.BeginRunPump(PumpComplete, null); }
public void Intercept(IInvocation invocation) { var pipename = Guid.NewGuid().ToString(); var procArgs = new List<string> { Quote(invocation.TargetType.AssemblyQualifiedName), Quote(invocation.MethodInvocationTarget.Name), pipename, }; procArgs.AddRange(invocation.Arguments.Select(a => Serialize(a))); var proc = new Process { StartInfo = { FileName = "runner.exe", Arguments = String.Join(" ", procArgs.ToArray()), UseShellExecute = false, CreateNoWindow = true, } }; using (var pipe = new NamedPipeServerStream(pipename, PipeDirection.In)) { proc.Start(); pipe.WaitForConnection(); var r = bf.Deserialize(pipe); r = r.GetType().GetProperty("Value").GetValue(r, null); proc.WaitForExit(); if (proc.ExitCode == 0) { invocation.ReturnValue = r; } else { var ex = (Exception) r; throw new Exception("Error in external process", ex); } } }
private void server() { System.IO.Pipes.NamedPipeServerStream pipeServer = new System.IO.Pipes.NamedPipeServerStream("testpipe", System.IO.Pipes.PipeDirection.InOut, 4); StreamReader sr = new StreamReader(pipeServer); StreamWriter sw = new StreamWriter(pipeServer); do { try { pipeServer.WaitForConnection(); string test; sw.WriteLine("Waiting"); sw.Flush(); pipeServer.WaitForPipeDrain(); test = sr.ReadLine(); Console.WriteLine(test); } catch (Exception ex) { throw ex; } finally { pipeServer.WaitForPipeDrain(); if (pipeServer.IsConnected) { pipeServer.Disconnect(); } } } while (true); }
public async void SendMessageAsync() { try { using (var pipe = new NamedPipeServerStream(verb, PipeDirection.Out, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) using (var stream = new StreamWriter(pipe)) { var connectionTask = Task.Factory.FromAsync(pipe.BeginWaitForConnection, pipe.EndWaitForConnection, null); var timeoutTask = Task.Delay(2000); var firstTask = await Task.WhenAny(connectionTask, timeoutTask); if (firstTask == timeoutTask) { pipe.EndWaitForConnection(connectionTask); return; } stream.AutoFlush = true; await stream.WriteLineAsync(selectedFile); } } catch (Exception exception) { //OnSendMessageException(pipeName, new MessengerExceptionEventArgs(exception)); } }
//NamedPipeServerStream owner; // .ctor with existing handle public UnixNamedPipeServer(NamedPipeServerStream owner, SafePipeHandle safePipeHandle) { this.handle = safePipeHandle; //this.owner = owner; }
// Using RunContinuationsAsynchronously for compat reasons (old API used ThreadPool.QueueUserWorkItem for continuations) internal ConnectionCompletionSource(NamedPipeServerStream server, CancellationToken cancellationToken) : base(server._threadPoolBinding, cancellationToken, pinData: null) { _serverStream = server; }
//NamedPipeServerStream owner; // .ctor with existing handle public Win32NamedPipeServer(NamedPipeServerStream owner, SafePipeHandle safePipeHandle) { handle = safePipeHandle; //this.owner = owner; }
// Using RunContinuationsAsynchronously for compat reasons (old API used ThreadPool.QueueUserWorkItem for continuations) internal ConnectionCompletionSource(NamedPipeServerStream server) : base(server._threadPoolBinding !, ReadOnlyMemory <byte> .Empty)
private void ListenNamedPipe() { var np = new System.IO.Pipes.NamedPipeServerStream(id.ToString(), System.IO.Pipes.PipeDirection.In, 1, System.IO.Pipes.PipeTransmissionMode.Byte, System.IO.Pipes.PipeOptions.Asynchronous); np.BeginWaitForConnection(AsyncCallback, np); }
static public async Task WriteAsync(this System.IO.Pipes.NamedPipeServerStream self, byte[] data) { await self.WriteAsync(data, 0, data.Length); }