public void SendToServer(PipeCommand command, int TimeOut = 5000) { try { if (_service.GetStatus() == "stopped") { Console.WriteLine("start service first"); return; } var serializedCommand = JsonConvert.SerializeObject(command); NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); pipeStream.Connect(TimeOut); StreamString ss = new StreamString(pipeStream); ss.SendCommand(serializedCommand); var answer = ss.ReadAnswer(); Console.WriteLine(answer); } catch (Exception ex) { Console.WriteLine("Error: " + "[" + ex.Source + "] " + ex.Message); } }
// This method will be called when the thread is started. public void DoWork() { NamedPipeServerStream pipeServer = new NamedPipeServerStream("mayhemSocketPipeName", PipeDirection.InOut, maxThreads); int threadId = Thread.CurrentThread.ManagedThreadId; // Wait for a client to connect //pipeServer.BeginWaitForConnection() pipeServer.WaitForConnection(); Logger.WriteLine(string.Format("Client connected on thread[{0}].", threadId)); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); Message = ss.ReadString(); } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Logger.WriteLine(string.Format("ERROR: {0}", e.Message)); } pipeServer.Close(); }
private static int ConnectToPipeServer(string name, string command) { var result = 0; var pipeClient = new NamedPipeClientStream( ".", name, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); try { pipeClient.Connect(10000); StreamString ss = new StreamString(pipeClient); ss.WriteString(command); Console.Out.WriteLine(ss.ReadString()); } catch (Exception e) { Console.Error.WriteLine(e.Message); result = -1; } finally { pipeClient.Close(); } return(result); }
private async void ServerThread() { while (!Cancellation.IsCancellationRequested) { try { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("ConvertZZ_Pipe", PipeDirection.InOut)) { await pipeServer.WaitForConnectionAsync(Cancellation.Token); Console.WriteLine("Client connected."); StreamString ss = new StreamString(pipeServer); string[] Args = (await ss.ReadStringAsync()).Split('|'); Window_DialogHost window_DialogHost = new Window_DialogHost(Args[0] == "/file" ? Enums.Enum_Mode.Mode.File_FileName : Enums.Enum_Mode.Mode.AutioTag, Args.Skip(1).ToArray()); window_DialogHost.Show(); await ss.WriteStringAsync("ACK"); pipeServer.WaitForPipeDrain(); pipeServer.Close(); } } catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } } }
private bool HandleProgramSingularity(string openedFilename) { try { NamedPipeClientStream pipe = new NamedPipeClientStream(".", Constants.PIPE_NAME, PipeDirection.Out); pipe.Connect(1000); if (openedFilename == null) { openedFilename = string.Empty; } StreamString ss = new StreamString(pipe); ss.WriteString(openedFilename); this.Shutdown(); return(false); } catch (Exception) { BackgroundWorker listener = new BackgroundWorker(); listener.DoWork += new DoWorkEventHandler(listener_DoWork); listener.RunWorkerAsync(); } return(true); }
private void ResetClient() { _stateLock.Wait(); _state = State.Disconnecting; _stateLock.Release(); try { _streamIn?.Dispose(); } catch (ObjectDisposedException) { } _streamIn = null; try { _streamOut?.Dispose(); } catch (ObjectDisposedException) { } _streamOut?.Dispose(); _streamOut = null; _ss = null; try { _cts?.Dispose(); } catch (ObjectDisposedException) { } _stateLock.Wait(); _state = State.Disconnected; _stateLock.Release(); }
/// <summary> /// Запуск канала /// </summary> public void StartPipe() { //Инициализация переменных int err = 0; m_bStopThread = false; m_ErrServ = 0; //Инициализация экземпляра канала m_pipeServer = new NamedPipeServerStream(m_NamePipe , PipeDirection.InOut , 1 , PipeTransmissionMode.Message , PipeOptions.Asynchronous , 1024 * 1024, 1024 * 1024); //Инициализация экземпляра класса по работе с каналом m_ss = new StreamString(m_pipeServer); waitConnect(out err);//Ожидание подключения //if (err == 0)//Если ошибок нет, соединение установлено //{ // m_thread = new Thread(ThreadRead);//Новый поток работы канала // m_thread.Start();//Старт потока //} }
// https://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows public static bool Startup(string instanceName, string pipeName) { _pipeName = pipeName; _cancellationSource = new CancellationTokenSource(); _singleInstanceMutex = new Mutex(true, instanceName, out bool createdNew); if (createdNew) { _producerThread = new Thread(ProducerLoop); _producerThread.Start(); return(true); } string[] args = Environment.GetCommandLineArgs(); if (args.Length != 2) { return(false); } // pass file on to the other instance using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous)) { StreamString io = new StreamString(client); client.Connect(500); // 500ms timeout io.WriteString($"OpenFile \"{args[1]}\""); } return(false); }
private static void ServerThread(object data) { NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, numThreads); int threadId = Thread.CurrentThread.ManagedThreadId; logger.Log(string.Format("Start Email thread[{0}].", threadId)); // Wait for a client to connect pipeServer.WaitForConnection(); logger.Log(string.Format("Client connected on Email thread[{0}].", threadId)); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. string content = ss.ReadString(); logger.Log(string.Format("Get Email message:\n{0}", content)); var CountArray = content.Length; var Subject = Settings.DefaultEmail_subject; var Body = String.Join("\n", content); MailAddress From = new MailAddress(Settings.DefaultSender); MailAddress To = new MailAddress(Settings.DefaultRecipient); var msg = new MailMessage(From, To) { Body = Body, Subject = Subject }; if (Settings.DefaultTo_copy != "") { string[] elements = Settings.DefaultTo_copy.Split(';'); foreach (var element in elements) { msg.CC.Add(new MailAddress(element.Trim())); } } var smtpClient = new SmtpClient(Settings.DefaultSmtpServer, Settings.DefaultServerPort) { Credentials = new NetworkCredential(Settings.DefaultLogin, Settings.DefaultPassword), EnableSsl = true }; smtpClient.Send(msg); } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { logger.Log(string.Format("Email ServerThread ERROR: {0}", e.Message), true); } pipeServer.Close(); }
private void RunClient() { try { _clientPipe = new NamedPipeClientStream(".", Constants.PipeName, Constants.PipeDirection, Constants.PipeOptions); _clientPipe.Connect(); _clientPipe.Flush(); _streamString = new StreamString(_clientPipe); Application.Current.Dispatcher.Invoke(() => { _parent.TextArea.Text = ""; }); do { if (_clientPipe != null && _clientPipe.IsConnected) { string line = _streamString.ReadString(); if (!string.IsNullOrWhiteSpace(line)) { if (line == Constants.DisconnectKeyword) { SendMessage(Constants.DisconnectKeyword); } else { Application.Current.Dispatcher.Invoke(() => { _parent.TextArea.Text = line; }); } } else { _serverClose = true; } } } while (!_serverClose); _clientPipe.Close(); Application.Current.Dispatcher.Invoke(() => { OnClientClosed(EventArgs.Empty); }); } catch (IOException) { _serverClose = true; _clientPipe.Flush(); _clientPipe.Close(); } catch (Exception ex) { throw ex; } }
/// <summary> /// Старт клиента /// </summary> public void StartClient() { int err = 0; m_b_stopThread = false; m_pipeName = string.Empty; //Инициализация экземпляра клиента m_client = new NamedPipeClientStream(m_serverName, "MainPipe", PipeDirection.InOut, PipeOptions.Asynchronous); //Инициализация объекта чтения и записи в поток(stream) m_ss = new StreamString(m_client); try { m_client.Connect(m_timeOut);//Попытка подключения к серверу } catch { } if (m_client.IsConnected == true)//Если подключен { b_IsConnected = m_client.IsConnected; SendConnect(); //Отправить сообщение серверу кто к нему подключился string ms = m_ss.ReadString(out err); //Должен вернуть имя канала к которому подключиться if (ms == "Non command") //Не понял команды и повторная попытка { SendConnect(); ms = m_ss.ReadString(out err); } m_pipeName = ms; m_Name = m_pipeName; SendDisconnect();//Отключаемся от основного канала b_IsConnected = m_client.IsConnected; m_client = null; //Инициализируем клиента с новым именем канала m_client = new NamedPipeClientStream(m_serverName, m_pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); m_ss = new StreamString(m_client); try { m_client.Connect(m_timeOut); //Подключаемся } catch { } if (m_client.IsConnected == true)//Если был подключен { b_IsConnected = m_client.IsConnected; SendConnect(); //Отправлям сообщение о подключениии thread = new Thread(ThreadRead); //Инициализация нового потока для работы канала thread.Start(); //Запуск потока b_Active = true; } } }
public void Connect() { try { if (_connected) { return; } do { try { //at server clientPipeRead->_pipeClientWrite var ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow)); if (_pipeClientWrite != null) { _pipeClientWrite.Close(); } //_pipeClientWrite.Dispose(); _pipeClientWrite = new NamedPipeServerStream("clientPipeRead", PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps); //if (_pipeServerWrite == null) // _pipeServerWrite = new NamedPipeServerStream("opcPipeRead", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps); _pipeClientWrite.WaitForConnection(); _ssWrite = new StreamString(_pipeClientWrite); if (_pipeClientRead != null) { _pipeClientRead.Close(); } //_pipeClientRead.Dispose(); _pipeClientRead = new NamedPipeServerStream("clientPipeWrite", PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps); _pipeClientRead.WaitForConnection(); _ssRead = new StreamString(_pipeClientRead); _connected = true; return; } catch (Exception ex) { if (ex.Message.Contains("The network path was not found")) { Thread.Sleep(TimeSleep); //wait for new connection } else { throw new Exception(ex.Message); } } } while (!_connected); } catch (Exception ex) { File.AppendAllText(_pathLog, "\r\n" + DateTime.Now.ToString() + ", ClientWinsService: " + ex.ToString()); } }
public static void UpdateMonitor() { Process.Start("NewMesMonitor.exe"); NamedPipeServerStream pipeServer = new NamedPipeServerStream("monitorpipe", PipeDirection.InOut, 1); // Wait for a client to connect pipeServer.WaitForConnection(); // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. ss.WriteString("Validating server"); while (Thread.CurrentThread.IsAlive) { string currentMonitorMessage = ""; foreach (ChatData chatData in chats) { if (chatData.CountNewMes == 0) { currentMonitorMessage += "There is no new messages with " + chatData.UserName + "\n"; } else { currentMonitorMessage += "There is " + chatData.CountNewMes + " new messages with " + chatData.UserName + "\n"; } } try { ss.WriteString(currentMonitorMessage); } catch (Exception e) { pipeServer.Close(); new Thread(UpdateMonitor) { IsBackground = true }.Start(); Thread.CurrentThread.Abort(); } Thread.Sleep(1000); } ss.WriteString("Close"); pipeServer.Close(); }
private static void ServerThread(object data) { NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, numThreads); int threadId = Thread.CurrentThread.ManagedThreadId; logger.Log(string.Format("Start Telegram thread[{0}].", threadId)); // Wait for a client to connect pipeServer.WaitForConnection(); logger.Log(string.Format("Client connected on Telegram thread[{0}].", threadId)); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. string content = ss.ReadString(); logger.Log(string.Format("Get Telegram message:\n{0}", content)); logger.Log(string.Format("GetIncomeMessages {0}", content.Contains("GetIncomeMessages()"))); if (content.Contains("GetIncomeMessages()")) { var msgs = botClient.GetIncomeMessages(); if (msgs == null) { msgs = "{[===[No new messages]===]}"; } ReadMessagesToStream msgsReader = new ReadMessagesToStream(ss, msgs); ss.ClearMessages += new OnReplyHandler(BotClient.ClearIncomeMessages); pipeServer.RunAsClient(msgsReader.Start); } else { botClient.Send(content); } } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { logger.Log(string.Format("Telegram ServerThread ERROR: {0}", e.Message), true); } pipeServer.Close(); }
public PipeConnection(string connectionName) { this.connectionName = connectionName; this.namedPipeClientStream = new NamedPipeClientStream( ".", connectionName, PipeDirection.InOut, PipeOptions.Asynchronous); this.streamString = new StreamString(namedPipeClientStream); }
public PipeConnection(string connectionName) { this.connectionName = connectionName; this.namedPipeServerStream = new NamedPipeServerStream( connectionName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); this.streamString = new StreamString(namedPipeServerStream); }
private static void ServerThread(object data) { //Creamos el pipe NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads); Console.WriteLine(StringResources.ServidorIniciado); while (true) { Console.WriteLine(StringResources.EsperandoConexion); //Esperamos conexiones pipeServer.WaitForConnection(); Console.WriteLine(StringResources.ClienteConectado); try { //Creamos un StreamString usando el pipe StreamString ss = new StreamString(pipeServer); //Recibimos el comando del cliente a través del Pipe string command = ss.ReadString(); Console.WriteLine(StringResources.ComandoRecibido+":"+command); //Ejecutamos el proceso,redirigiendo la salida al pipe ProcessStartInfo pinfo = new ProcessStartInfo(); pinfo.UseShellExecute = false; pinfo.RedirectStandardOutput = true; pinfo.FileName= ConfigurationManager.AppSettings.Get("powershellPath"); pinfo.Arguments = '"'+command+ '"'; using(Process process = Process.Start(pinfo)) { using (StreamReader reader = process.StandardOutput) { String line = reader.ReadLine(); while ( line != null ) { ss.WriteString(line); line = reader.ReadLine(); } ss.WriteString("##END##"); Console.WriteLine(StringResources.ComandoTerminado); } } } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } pipeServer.Disconnect(); } }
public void onClientConnect(IAsyncResult result) { Debug.Log("Client has connected to pipeServer."); pipeStreamString = new StreamString(pipeServer); String message = "VRE to SAPTranslator: Beginning inter-process communication. Do you read me?"; Debug.Log(message); pipeStreamString.WriteString(message); sendString("VRE to SAPTranslator: initialize(false)"); }
private static void sendMessage(string message) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "RABootPipe", PipeDirection.Out, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Impersonation); Console.WriteLine("Attempting to connect to pipe"); pipeClient.Connect(); Console.WriteLine("Successfully connected to pipe. Attempting to write " + message); StreamString ss = new StreamString(pipeClient); ss.WriteString(message); Console.WriteLine("Wrote message to pipe."); }
static void Main(string[] args) { var cli = new NamedPipeClientStream(".", "PingPong", PipeDirection.InOut); Console.WriteLine("Connecting to server...\n"); cli.Connect(); StreamString ss = new StreamString(cli); ss.WriteString("PING"); var received = ss.ReadString(); System.Diagnostics.Debug.Assert(received.StartsWith("PONG")); cli.Close(); }
public static decimal[] PipeConnectionProcess(NamedPipeClientStream pipeClient) { StreamString reader = new StreamString(pipeClient); var s = reader.ReadString(); if (s.Equals("end")) { return(null); } List <string> parsedNumbers = s.Split(' ').ToList(); List <decimal> numbers = parsedNumbers.Select(x => Decimal.Parse(x)).ToList(); return(numbers.ToArray()); }
private void backgroundWorker_Unity_Writer(object sender, DoWorkEventArgs e) { try { NPtoGUI = new NamedPipeClientStream(".", "NPtoGUI", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None); NPtoGUI.Connect(); clientStream = new StreamString(NPtoGUI); } catch (Exception ex) { //updateTextBuffer(ex.Message + Environment.NewLine + ex.StackTrace.ToString() + Environment.NewLine + "Last Message was: " + textBuffer); } }
public void TestVogalInvalid() { StreamString stream = new StreamString("aaaaaaaaa"); char resultado; try { resultado = stream.firstChar(stream); } catch (System.Exception) { resultado = ' '; } Assert.IsTrue(resultado == ' '); }
private static void Main(string[] args) { var pipeServerStream = new NamedPipeServerStream(Common.PipeName, PipeDirection.Out, 1); pipeServerStream.WaitForConnection(); var streamString = new StreamString(pipeServerStream); streamString.WriteString(Common.Secret); Console.WriteLine("Server ends"); pipeServerStream.Close(); Console.Read(); }
/// <summary> /// Старт клиента /// </summary> public void StartClient() { int err = 0; string ms = string.Empty; m_bStopThread = false; m_pipeName = string.Empty; //Инициализация экземпляра клиента m_client = new NamedPipeClientStream(m_serverName, NAME_MAINPIPE, PipeDirection.InOut, PipeOptions.Asynchronous); //Инициализация объекта чтения и записи в поток(stream) m_ss = new StreamString(m_client); connectToServer(); if (m_client.IsConnected == true) //Если подключен { SendConnect(); //Отправить сообщение серверу кто к нему подключился ms = m_ss.ReadString(out err); //Должен вернуть имя канала к которому подключиться //if (err == 0) { if (ms.Equals(MESSAGE_UNRECOGNIZED_COMMAND) == true) //Не понял команды и повторная попытка { SendConnect(); ms = m_ss.ReadString(out err); } m_pipeName = m_Name = ms; SendDisconnect(); //Отключаемся от основного канала //} else ; m_client = null; //Инициализируем клиента с новым именем канала m_client = new NamedPipeClientStream(m_serverName, m_pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); m_ss = new StreamString(m_client); connectToServer(); if (m_client.IsConnected == true) //Если был подключен { SendConnect(); //Отправлям сообщение о подключениии _thread = new Thread(fThread); //Инициализация нового потока для работы канала _thread.Start(); //Запуск потока b_Active = true; } } }
private static async void ProducerLoop() { try { while (!_shutdown) { try { using (_pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) { await _pipeServer.WaitForConnectionAsync(_cancellationSource.Token); if (!_pipeServer.IsConnected || _shutdown) { return; } StreamString io = new StreamString(_pipeServer); while (_pipeServer.IsConnected) { string commandLine = io.ReadString(); if (commandLine == null || _shutdown) { break; } Debug.WriteLine("Command received via NamedPipe: " + commandLine); if (!string.IsNullOrWhiteSpace(commandLine)) { ExternalCommand command = new ExternalCommand(commandLine); CommandLineQueue.Enqueue(command); var result = command.WaitForResult(TimeSpan.FromMilliseconds(2000)); io.WriteString((result.Success ? "OK" : "FAIL") + ":" + result.Message); } } } } catch (Exception ex) { Debug.WriteLine("InstanceHandler.ProducerLoop: " + ex.Message); } } } catch (OperationCanceledException) { } catch (ThreadAbortException) { } }
private void Upload(StreamString streamString, SerialPort serialPort, string fileName) { ConsoleEx.WriteLine(ConsoleColor.Yellow, $"UPLOAD ¨\"{fileName}\""); try { //--- Načteme řádky programu var lines = File.ReadAllLines(fileName); var file = Path.GetFileName(fileName); //--- ConsoleEx.WriteLine("---[ START ]---"); SendCmd(serialPort, $"file.remove('{file}')"); SendCmd(serialPort, $"file.open('{file}', 'w+')"); SendCmd(serialPort, "w = file.writeline"); foreach (var line in lines) { streamString.WriteString(line); SendLua(serialPort, line); } ConsoleEx.NewLine(); SendCmd(serialPort, "file.close()"); ConsoleEx.WriteLine("---[ END ]---"); ConsoleEx.WriteLine($"{_SendedLines} line(s) sended"); } catch (DirectoryNotFoundException ex) { ConsoleEx.NewLine(); ConsoleEx.WriteError(ex); } catch (Exception ex) { ConsoleEx.NewLine(); ConsoleEx.WriteError(_SendedLines <= 0 ? $"---[ ERROR ]---" : $"---[ ERROR in line {_SendedLines} ]---"); ConsoleEx.WriteError(ex); ConsoleEx.WriteLine("Do you have correct the PortName?"); } finally { ConsoleEx.NewLine(); } }
void listener_DoWork(object sender, DoWorkEventArgs e) { while (true) { NamedPipeServerStream pipe = new NamedPipeServerStream(Constants.PIPE_NAME, PipeDirection.In, 1); pipe.WaitForConnection(); StreamString ss = new StreamString(pipe); string openedFilename = ss.ReadString(); this.Dispatcher.Invoke(this.processFileDelegate, openedFilename); pipe.Close(); } }
public static void SendPipedMessage(StreamString streamString, string message) { try { if (!string.IsNullOrWhiteSpace(message)) { if (streamString != null) { streamString.WriteString(message); } } } catch (Exception ex) { throw ex; } }
public static void Main(string[] Args) { if (Args.Length > 0) { if (Args[0] == "spawnclient") { /** * Robust Programming * The client and server processes in this example are intended to run on the same computer, * so the server name provided to the NamedPipeClientStream object is ".". * If the client and server processes were on separate computers, * "." would be replaced with the network name of the computer that runs the server process. */ NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); Console.WriteLine("Connecting to server...\n"); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); // Validate the server's signature string if (ss.ReadString() == "I am the one true server!") { // The client security token is sent with the first write. // Send the name of the file whose contents are returned // by the server. ss.WriteString("c:\\textfile.txt"); // Print the file to the screen. Console.Write(ss.ReadString()); } else { Console.WriteLine("Server could not be verified."); } pipeClient.Close(); // Give the client process some time to display results before exiting. Thread.Sleep(4000); } } else { Console.WriteLine("\n*** Named pipe client stream with impersonation example ***\n"); StartClients(); } }
private void WaitForConnectionCallBack(IAsyncResult ar) { if (!this.isStopping) { this.pipeServer.EndWaitForConnection(ar); OnClientConnect(); IStreamString ss = new StreamString(this.pipeServer); var conArgs = new RequestDigestEventArgs() { StreamString = ss }; ConnectionStablished(this, conArgs); Stop(); OnClientDisconnect(); } }
/// <summary> /// Send a message to a NAPS2 instance running a pipe server. /// </summary> /// <param name="recipient">The process to send the message to.</param> /// <param name="msg">The message to send.</param> public static bool SendMessage(Process recipient, string msg) { try { using (var pipeClient = new NamedPipeClientStream(".", GetPipeName(recipient), PipeDirection.Out)) { //MessageBox.Show("Sending msg:" + msg); pipeClient.Connect(TIMEOUT); var streamString = new StreamString(pipeClient); streamString.WriteString(msg); //MessageBox.Show("Sent"); return true; } } catch (Exception e) { Log.ErrorException("Error sending message through pipe", e); return false; } }
public static void Main(string[] Args) { if (Args.Length > 0) { if (Args[0] == "spawnclient") { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); Console.WriteLine("Connecting to server...\n"); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); // Validate the server's signature string if (ss.ReadString() == "I am the one true server!") { // The client security token is sent with the first write. // Send the name of the file whose contents are returned // by the server. ss.WriteString(@"C:\Temp\textfile.txt"); // Print the file to the screen. Console.Write(ss.ReadString()); } else { Console.WriteLine("Server could not be verified."); } pipeClient.Close(); // Give the client process some time to display results before exiting. Thread.Sleep(4000); } } else { Console.WriteLine("\n*** Named pipe client stream with impersonation example ***\n"); StartClients(); } }
private static void ServerThread(object data) { NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads); int threadId = Thread.CurrentThread.ManagedThreadId; // Wait for a client to connect pipeServer.WaitForConnection(); Console.WriteLine("Client connected on thread[{0}].", threadId); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. ss.WriteString("I am the one true server!"); string filename = ss.ReadString(); // Read in the contents of the file while impersonating the client. ReadFileToStream fileReader = new ReadFileToStream(ss, filename); // Display the name of the user we are impersonating. Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.", filename, threadId, pipeServer.GetImpersonationUserName()); pipeServer.RunAsClient(fileReader.Start); } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } pipeServer.Close(); }
private static void ServerThread(object data) { NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads); int threadId = Thread.CurrentThread.ManagedThreadId; //wait for client to connect pipeServer.WaitForConnection(); Console.WriteLine("Client connected on thread[{0}].", threadId); try { //Read the request from the client. Once the client has //written to the pipe its security token will be available. //We might not need this security token ? //We need interprocess communication on the same computer StreamString ss = new StreamString(pipeServer); //Verify our identity to the connected client using a //string that the client anticipates ss.WriteString("I am the one true server!"); string filename = ss.ReadString(); //Read in the contents of the file while impersonating the client. ReadFileToStream fileReader = new ReadFileToStream(ss, filename); //Display the name of the user we are impersonating. //Impersonating ? Console.WriteLine("Reading file: {0} on thread{1} as user: {2}.", filename, threadId, pipeServer.GetImpersonationUserName()); //So impersonation is nothing but name of client at the other end ? Cool! pipeServer.RunAsClient(fileReader.Start); } catch(IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } pipeServer.Close(); }
/// <summary> /// Start a pipe server on a background thread, calling the callback each time a message is received. Only one pipe server can be running per process. /// </summary> /// <param name="msgCallback">The message callback.</param> public static void StartServer(Action<string> msgCallback) { if (_serverRunning) { return; } var thread = new Thread(() => { try { using (var pipeServer = new NamedPipeServerStream(GetPipeName(Process.GetCurrentProcess()), PipeDirection.In)) { while (true) { pipeServer.WaitForConnection(); var streamString = new StreamString(pipeServer); var msg = streamString.ReadString(); //MessageBox.Show("Received msg:" + msg); if (msg == MSG_KILL_PIPE_SERVER) { break; } msgCallback(msg); pipeServer.Disconnect(); } } } catch (Exception ex) { Log.ErrorException("Error in named pipe server", ex); } _serverRunning = false; }); _serverRunning = true; thread.Start(); }
static void TestClient(object stateInfo) { Console.WriteLine("entering TestClient"); NamedPipeClientStream pipeClient1 = new NamedPipeClientStream(".", "openclmonitor_pipe", PipeDirection.InOut, PipeOptions.None); pipeClient1.Connect(5000); if (!pipeClient1.IsConnected) { Console.WriteLine("TestClient KO;Could not connect to pipe"); return; } StreamString ss = new StreamString(pipeClient1); MonitorMessage createMsgOUT = new MonitorMessage(OpCodes.CREATE, 0, 0, "DEVICETEST"); ss.WriteString(createMsgOUT.ToString()); MonitorMessage createMsgIN = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", createMsgIN.ToString()); pipeClient1.Close(); NamedPipeClientStream pipeClient2 = new NamedPipeClientStream(".", createMsgIN.Body[0], PipeDirection.InOut, PipeOptions.None); pipeClient2.Connect(5000); if (!pipeClient2.IsConnected) { Console.WriteLine("TestClient KO;Could not connect to queue pipe"); return; } ss = new StreamString(pipeClient2); MonitorMessage enumOUT = new MonitorMessage(OpCodes.ENUMERATE_COUNTERS, 0, 0, new string[] { "counterA", "counterB" }); ss.WriteString(enumOUT.ToString()); MonitorMessage enumIN = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", enumIN.ToString()); StringBuilder sb = new StringBuilder(); sb.Append("TestClient received enable counters: "); foreach (int cid in enumIN.BodyAsFloatArray) { sb.AppendFormat("{0}, ", cid); } Console.WriteLine(sb.ToString()); { MonitorMessage mOut = new MonitorMessage(OpCodes.PERF_INIT, 0, 0); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } { MonitorMessage mOut = new MonitorMessage(OpCodes.RELEASE, 0, 0); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } { MonitorMessage mOut = new MonitorMessage(OpCodes.GET_COUNTERS, 0, 0, new float[]{1.1f, 2.2f}); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } { MonitorMessage mOut = new MonitorMessage(OpCodes.END, 0, 0); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } pipeClient2.Close(); Console.WriteLine("TestClient queue done"); }
/// <summary> /// Sólo recibe la información del servidor,no interactúa con este /// </summary> /// <param name="command">Comando que se desea lanzar en el servidor</param> /// <returns>True si se ha ejecutado correctamente /// False si ha habido algún problema /// </returns> private bool runBatchTool(string command) { pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); //Enviamos el comando ss.WriteString(command); //Leemos la salida gradualmente mientras el servidor no acaba la ejecución del comando String output = ss.ReadString(); //Mientras el servidor no envie ##END##, sigue enviando el output de la herramienta while (output != "##END##") { try { parseOutput(command, output); output = ss.ReadString(); } catch (Exception e) { Console.WriteLine(e.Message+"\n"+e.StackTrace); return false; } } return true; }
private bool HandleProgramSingularity(string openedFilename) { try { NamedPipeClientStream pipe = new NamedPipeClientStream(".", Constants.PIPE_NAME, PipeDirection.Out); pipe.Connect(1000); if (openedFilename == null) { openedFilename = string.Empty; } StreamString ss = new StreamString(pipe); ss.WriteString(openedFilename); this.Shutdown(); return false; } catch (Exception) { BackgroundWorker listener = new BackgroundWorker(); listener.DoWork += new DoWorkEventHandler(listener_DoWork); listener.RunWorkerAsync(); } return true; }
public ReadFileToStream(StreamString str, string filename) { fn = filename; ss = str; }
public void ServerThread() { NamedPipeServerStream pipeServer = new NamedPipeServerStream("FTPbox Server", PipeDirection.InOut, 5); int threadID = Thread.CurrentThread.ManagedThreadId; pipeServer.WaitForConnection(); Log.Write(l.Client, "Client connected, id: {0}", threadID); try { StreamString ss = new StreamString(pipeServer); ss.WriteString("ftpbox"); string args = ss.ReadString(); ReadMessageSent fReader = new ReadMessageSent(ss, "All done!"); Log.Write(l.Client, "Reading file: \n {0} \non thread [{1}] as user {2}.", args, threadID, pipeServer.GetImpersonationUserName()); List<string> li = new List<string>(); li = ReadCombinedParameters(args); CheckClientArgs(li.ToArray()); pipeServer.RunAsClient(fReader.Start); } catch (IOException e) { Common.LogError(e); } pipeServer.Close(); }