// 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 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; } }
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(); } }
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(); //<snippet2> 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(); //</snippet2> // 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 Main(string[] args) { var pipeClient = new NamedPipeClientStream(".", Common.PipeName, PipeDirection.InOut, PipeOptions.None); pipeClient.Connect(); var streamString = new StreamString(pipeClient); //Client read content from pipe if (streamString.ReadString() == Common.Secret) { // Client write content to pipe streamString.WriteString("E:\\Projects\\git\\NamedPipeSpike\\message.txt"); } // Client read content again, expecting server has written at this moment to the pipe Console.WriteLine($"Server send back file content: {streamString.ReadString()}"); Console.ReadKey(); }
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 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) { //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 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()); }
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(); }
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) { } }
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(); } }
private void backgroundWorker_Unity_Reader(object sender, DoWorkEventArgs e) { try { NPtoUnity = new NamedPipeClientStream(".", "NPtoUnity", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None); NPtoUnity.Connect(); StreamString clientStream = new StreamString(NPtoUnity); while (true) { dataFromGUI = clientStream.ReadString(); } } catch (Exception ex) { //updateTextBuffer(ex.Message + Environment.NewLine + ex.StackTrace.ToString() + Environment.NewLine + "Last Message was: " + textBuffer); } }
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 { //<snippet2> // 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); //</snippet2> } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } pipeServer.Close(); }
public static void ServerThread() { print("Waiting client to connect\n"); // Wait for a client to connect pipeServer.WaitForConnection(); print("Connected\n"); StreamString ss = new StreamString(pipeServer); while (true) { string messages = ""; if (ss.ReadString(ref messages)) { //Console.WriteLine("Read : " + messages); print("Read : " + messages); } } }
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(); }
public static Response SendRequest(Request request, Stream pipeClient, Action <string, string> loggingFunction) { loggingFunction(MethodBase.GetCurrentMethod().Name, "Sending request to service..."); var streamString = new StreamString(pipeClient); loggingFunction(MethodBase.GetCurrentMethod().Name, "Serializing request..."); var requestXml = ServiceBrokerProtocolHelper.Serialize(request); loggingFunction(MethodBase.GetCurrentMethod().Name, "Transmitting request..."); // Send request streamString.WriteString(requestXml); loggingFunction(MethodBase.GetCurrentMethod().Name, "Request sent to service."); loggingFunction(MethodBase.GetCurrentMethod().Name, "Receiving response from service..."); //Recieve the response var response = ServiceBrokerProtocolHelper.Deserialize <Response>(streamString.ReadString()); loggingFunction(MethodBase.GetCurrentMethod().Name, string.Format(CultureInfo.CurrentCulture, "Response received from service: Code={0}, MessageBody={1}", response.ResponseCode, response.MessageBody)); return(response); }
//this is the main function used by the thread that communicates with the RABooter. //When it receives a message, it will interpret the message as a filepath and attempt to launch the routine. private static void ScheduleThread(int[] macroKeys) { pipeServer = new NamedPipeServerStream("RABootPipe", PipeDirection.In, 5); int threadId = Thread.CurrentThread.ManagedThreadId; while (!interruptFlag) { //This function will wait forever until a client connects pipeServer.WaitForConnection(); if (interruptFlag) { return; } try { //Reads a string in from the pipe StreamString ss = new StreamString(pipeServer); string message = ss.ReadString(); Thread interruptThread = new Thread(() => { interruptInterpreterSequence(macroKeys); }); interruptThread.Start(); //the message from the pipe contains the file path for the routine to be executed. executeAutomatedRoutine(message, 1, 1); try { pipeServer.Disconnect();//this is sometimes crashing it } catch (InvalidOperationException ex) { Console.Write(ex); } Thread.Sleep(1000); } catch (IOException e) { Console.WriteLine("ERR: " + e.Message); } } }
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(); }
/// <summary> /// Creates a named pipe server and waits for input. /// </summary> private static void CreatePipeThread() { try { while (true) { NamedPipeServerStream pipeServer = new NamedPipeServerStream("GrepPipStreamInput", PipeDirection.In); pipeServer.WaitForConnection(); 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); string text = ss.ReadString(); if (SearchPatternReceived != null) { string searchText = text.Substring(text.IndexOf("?") + 1); string directory = text.Substring(0, text.IndexOf("?")); SearchPatternReceived(directory, searchText); } } catch (Exception ex) { Logger.get().AddError(ex.Message); } finally { pipeServer.Close(); } } } catch { } }
private static void Main(string[] args) { var pipeServer = new NamedPipeServerStream(Common.PipeName, PipeDirection.InOut, 1); pipeServer.WaitForConnection(); var streamString = new StreamString(pipeServer); // Server write to pipe streamString.WriteString(Common.Secret); // Server wait for client writing, then read it from pipe var fileName = streamString.ReadString(); // Server write content back to pipe var content = File.ReadAllText(fileName); streamString.WriteString(content); pipeServer.Close(); Console.WriteLine("Server finishes"); Console.Read(); }
private void ServerThread(object data) { var handleMsg = (Action <string>)data; using var pipeServer = new NamedPipeServerStream(Name, PipeDirection.InOut); // Wait for a client to connect pipeServer.WaitForConnection(); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. var ss = new StreamString(pipeServer); var msg = ss.ReadString(); handleMsg(msg); } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Trace.TraceError("ERROR: {0}", e.Message); } }
public void ServerWaitForMessages() { new Thread(() => { cmd = ""; ss = new StreamString(pipe); while (cmd != "CLOSE") { try { buffer = new char[256]; text = ""; msg = ss.ReadString().ToUpper(); word = msg.Split(' '); cmd = word[0].ToUpper(); for (i = 1; i < word.Length; i++) text += word[i] + " "; switch (cmd) { case "AUTHENTICATE": ss.WriteString("I am PIPE1 server"); break; case "SOMEPIPEREQUEST":ss.WriteString(doSomePipeRequestReturningString()):break; case "CLOSE": ss.WriteString("CLOSE");// reply to client Thread.Sleep(1000);// wait for client to pick-up shutdown message pipe.Close(); Act.m.md.Msg("Server Shutdown ok"); // Server side message break; } } catch (IOException iox) { string error = iox.Message; Act.m.md.Msg(error); break; } } }).Start(); }
/// <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(); }
public void sendString(string message) { if (pipeStreamString == null) { Debug.Log("Tried to send message \"" + message + "\" to SAPTranslator, but SAPTranslator has not connected to pipe."); return; } else { string pipeContent = pipeStreamString.ReadString(); if (pipeContent != null) { Debug.Log(pipeContent); } if (pipeContent.Equals("SAPTranslator to VRE: awaiting command")) { Debug.Log(message); pipeStreamString.WriteString(message); pipeServer.WaitForPipeDrain(); if (message.Contains("resultsFrameJointForce")) { frameJointForce frameJointForceObject = readResponseResultsFrameJointForce(); myAnalysisController.setLatestFrameJointForceResult(frameJointForceObject); } else if (message.Contains("resultsFrameForce")) { frameForce frameForceObject = readResponseResultsFrameForce(); myAnalysisController.setLatestFrameForceResult(frameForceObject); } else if (message.Contains("resultsJointDispl") || message.Contains("customResultsGetFrameSpecialPointDispl")) { jointDispl jointDisplObject = readResponseResultsJointDispl(); myAnalysisController.setLatestJointDisplResult(jointDisplObject); } } } }
/// <param name="args"></param> private static void Main(string[] args) { ConsoleEx.WriteAppCaption(); //--- Analyzujeme příkazovou řádku var cmdLine = new MyCommandLine(args); //je help? if (cmdLine.ExistsAny(new[] { PAR_HELP_1, PAR_HELP_2, PAR_HELP_3 })) { ShowHelp(); return; } var pipeName = cmdLine.Value(PAR_PIPE_NAME); if (string.IsNullOrEmpty(pipeName)) { ConsoleEx.WriteLine("Missing name of pipe."); ShowHelp(); return; } MessageFromClient message = null; try { message = GetMessage(cmdLine); } catch (Exception ex) { ConsoleEx.WriteError(ex); ShowHelp(); return; } if (message == null) { ConsoleEx.WriteLine("Missing command."); ShowHelp(); return; } try { using (var pipeClient = new NamedPipeClientStream( "." , pipeName , PipeDirection.InOut , PipeOptions.None , TokenImpersonationLevel.Impersonation)) { pipeClient.Connect(500); ConsoleEx.WriteLine($"Connect to pipe '{pipeName}' successed."); var streamString = new StreamString(pipeClient); streamString.WriteString(JsonConvert.SerializeObject(message)); do { ConsoleEx.WriteLine(ConsoleColor.White, streamString.ReadString()); } while (pipeClient.IsConnected); pipeClient.Close(); return; } } catch (Exception ex) { ConsoleEx.WriteError(ex); ConsoleEx.WriteError($"Connect to {pipeName} failed."); } //--- Debug.WriteLine($"Connect to {pipeName} failed."); }
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(); }
private void StartNamedPipeServer() { new Thread(() => { var done = false; do { NamedPipeServerStream pipeServer = null; try { CreatePowerShellRunspace(); _runspace.Open(); var commonAdminFunctions = new CommonAdminFunctions(ref _runspace, (method, message) => { LogMessage(string.Format(CultureInfo.CurrentCulture, "{0}:{1}", method, message), EventLogEntryType.Information); }); var security = new PipeSecurity(); security.AddAccessRule(new PipeAccessRule(@"NT Service\AccountName", PipeAccessRights.FullControl, AccessControlType.Allow)); security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow)); security.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow)); pipeServer = new NamedPipeServerStream(StringConstants.TechServicePipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, security); var threadId = Thread.CurrentThread.ManagedThreadId; LogMessage("Waiting for connection on thread..." + threadId, EventLogEntryType.Information); pipeServer.WaitForConnection(); var ss = new StreamString(pipeServer); var rawProtocolRequest = ss.ReadString(); var request = ServiceBrokerProtocolHelper.Deserialize <Request>(rawProtocolRequest); var noResultResponse = new Response { MessageBody = String.Empty, ResponseCode = ResponseCode.None }; var response = noResultResponse; LogMessage(string.Format(CultureInfo.CurrentCulture, "Received new message from plugin. Type={0} MessageBody={1}", request.RequestTask, request.MessageBody), EventLogEntryType.Information); try { switch (request.RequestTask) { case RequestTask.Task1: Task1(request.MessageBody); response = noResultResponse; break; case RequestTask.Task2: Task2(request.MessageBody); response = noResultResponse; break; case RequestTask.StopNamedPipeServer: done = true; LogMessage("Shutting down named pipe server thread on request.", EventLogEntryType.Information); response = noResultResponse; break; default: LogMessage("Unknown message received from broker plugin:" + rawProtocolRequest, EventLogEntryType.Error); response = noResultResponse; break; } } catch (Exception e) { // Problem while running any of the admin functions? Send back an error response var logMessage = "Error occured while running protocol request:" + e.Message; LogMessage(logMessage, EventLogEntryType.Error); response = new Response { ResponseCode = ResponseCode.Error, MessageBody = logMessage }; } finally { // We will *always* send the response of some sort. // This serves in the very least as an acknowledgement of pipe function being finished either successfully or unsuccessfully depending on the response code LogMessage(string.Format(CultureInfo.CurrentCulture, "Sending response of '{0}' type='{1}'", response.MessageBody, response.ResponseCode), EventLogEntryType.Information); ss.WriteString(ServiceBrokerProtocolHelper.Serialize(response)); } } catch (Exception e) { // Problem with the named pipe functionality? Send back an error response var message = string.Format(CultureInfo.CurrentCulture, "Unexpected exception occured setting up named pipe. Message = '{0}', StackTrace = {1}", e.Message, e.StackTrace); LogMessage(message, EventLogEntryType.Error); } finally { LogMessage("Finished with connection...", EventLogEntryType.Information); // Note if this thread is aborted such as when the service restarts, this is guarenteed still to run, freeing up resources in this thread... if (pipeServer != null) { LogMessage("Closing server pipe.", EventLogEntryType.Information); pipeServer.Close(); } ClosePowerShellRunspace(); } } while (!done); }).Start(); }
internal string WaitMessage() { return(streamString.ReadString()); }
/// <summary> /// Forces the user to log into the web service. /// </summary> /// <param name="state">The thread start parameter.</param> void PipeThread(Object state) { try { NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream("Silopipe"); Int32 threadId = Thread.CurrentThread.ManagedThreadId; // Wait for a client to connect namedPipeServerStream.WaitForConnection(); while (this.isPipeThreadRunning) { Boolean isHandled = false; try { // Read the request from the client. Once the client has written to the pipe its security token will be available. StreamString streamString = new StreamString(namedPipeServerStream); String query = streamString.ReadString(); if (query == String.Empty) { Thread.Sleep(100); continue; } DateTime startTime = DateTime.Now; // Make sure the account data is loaded for the given date and account combination. Match scalarMatch = MainWindow.scalarRegex.Match(query); if (scalarMatch.Success) { String tableName = scalarMatch.Groups["tableName"].Value; String whereClause = scalarMatch.Groups["whereClause"].Value; String selectClause = scalarMatch.Groups["selectClause"].Value; IEnumerable iEnumerable = DataModel.Tables[tableName] as IEnumerable; if (iEnumerable != null) { Decimal total = 0.0m; var result = iEnumerable.AsQueryable().Where(whereClause).GroupBy("TaxLotRow.PositionRow.AccountId", "it").Select(selectClause); foreach (Decimal sum in result) { total += sum; } streamString.WriteString(total.ToString()); } isHandled = true; } Console.WriteLine("Time {0}: {1}", DateTime.Now.Subtract(startTime).TotalMilliseconds, query); if (!isHandled) { streamString.WriteString("#Syntax Error"); } } catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } } namedPipeServerStream.Close(); } catch { } }
private void StartPipeServer() { while (true) { try { using (var pipeServer = new NamedPipeServerStream(_PipeName, PipeDirection.InOut, 1)) { ConsoleEx.WriteLine($"Pipe server '{_PipeName}' waiting for connection."); pipeServer.WaitForConnection(); // Wait for a client to connect Console.WriteLine("Pipe client connected."); lock (Helpers.Locker) { try { var streamString = new StreamString(pipeServer); var msg = JsonConvert.DeserializeObject <MessageFromClient>(streamString.ReadString()); streamString.WriteString("Ok"); Console.WriteLine($"Command: {msg.Command}"); switch (msg.Command) { case "UPLOAD": foreach (var parameter in msg.Parameters) { Upload(streamString, _SerialPort, parameter); } break; case "DOFILE": foreach (var parameter in msg.Parameters) { var file = Path.GetFileName(parameter); SendCmd(_SerialPort, $"dofile('{file}')"); } break; case "CMD": foreach (var parameter in msg.Parameters) { SendCmd(_SerialPort, parameter); } break; } } catch (IOException ex) { ConsoleEx.WriteError(ex); } catch (Exception ex) { ConsoleEx.WriteError(ex); } } pipeServer.Close(); } } catch (IOException ex) { ConsoleEx.WriteError(ex); } } }
private async Task RunServerAsync() { try { if (_serverPipe != null) { await Task.Factory.FromAsync( (cb, state) => _serverPipe.BeginWaitForConnection(cb, state), ar => _serverPipe.EndWaitForConnection(ar), null); bool clientDisconnected = false; _streamString = new StreamString(_serverPipe); Application.Current.Dispatcher.Invoke(() => { _parent.TextArea.Text = ""; }); SendMessage("initialised"); while (true) { if (_serverPipe != null && _serverPipe.IsConnected) { string line = string.Empty; try { line = _streamString.ReadString(); } catch (Exception ex) { Console.WriteLine(ex); } if (!string.IsNullOrWhiteSpace(line)) { if (line == Constants.DisconnectKeyword) { break; } else { Application.Current.Dispatcher.Invoke(() => { _parent.TextArea.Text = line; }); } } else if (string.IsNullOrWhiteSpace(line)) { break; } } else if (!_serverPipe.IsConnected) { clientDisconnected = true; break; } } if (clientDisconnected) { Application.Current.Dispatcher.Invoke(() => { OnClientDisconnect(EventArgs.Empty); }); clientDisconnected = false; } PipeFlushClose(_serverPipe); Application.Current.Dispatcher.Invoke(() => { OnServerClosed(EventArgs.Empty); }); } } catch (Exception ex) { throw ex; } }
static void Main(string[] args) { string pipeName; TcpListenerManager listenerManager = null; Socket host = null; Socket tablet = null; ClientHandler cHandler = null; Thread clientThread = null; Thread observerThread = null; string RoomName; string port; byte[] buffer = new byte[128]; //실행 매개변수는 pipe name과 방의 이름이다. if (args.Length == 2) { RoomName = args[0]; pipeName = args[1]; } else { Console.WriteLine("Argument is invalied"); foreach (var arg in args) { Console.WriteLine(arg); } Environment.Exit(0); return; } NamedPipeClientStream pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut); pipe.Connect(); var ss = new StreamString(pipe); if (ss.ReadString() == "NameServer::StartRoom") //>>1 { port = ss.ReadString(); //>>4 try { listenerManager = new TcpListenerManager(port); listenerManager.StartListening(); while (true) { //Drawing Server에 연결되면 Client는 최초로 자신에 대해 전송한다. Socket temp = listenerManager.TcpListener.AcceptSocket(); int recvSize = temp.Receive(buffer, buffer.Length, SocketFlags.None); if (recvSize > 0) { string message = Encoding.UTF8.GetString(buffer, 0, recvSize); string[] toks = message.Split(AppData.Delimiter); foreach (var tok in toks) { if (tok == "") { continue; } if (tok.Contains(AppData.ServerCommand)) { if (tok == AppData.ServerCommand + "Host") { host = temp; } else if (tok == AppData.ServerCommand + "Tablet") { tablet = temp; } else if (tok == AppData.ServerCommand + "Guest") { } } } } else { var message = Encoding.UTF8.GetBytes("@FAIL"); temp.Send(buffer, buffer.Length, SocketFlags.None); continue; } // host와 host tablet이 접속해야 실제 Drawing을 시작한다. if (host == null || tablet == null) { continue; } else { if (clientThread == null) { cHandler = new ClientHandler(host, tablet, RoomName); clientThread = new Thread(new ThreadStart(cHandler.RunDrawing)); clientThread.Start(); //Drawing Thread를 Join하고 Listen loop를 끝내기 위한 Observer Thread var observer = new ThreadObserver(clientThread, listenerManager); observerThread = new Thread(new ThreadStart(observer.runObserving)); observerThread.Start(); } else { //현재 포함된 Guest의 수를 확인하고 지정된 수보다 적으면 접속, 아니면 실패를 통지 if (cHandler.GuestEnterRequest()) { cHandler.GuestEnter(temp); } else { var message = Encoding.UTF8.GetBytes(CommendBook.DRAWING_ROOM_FULL); temp.Send(message, message.Length, SocketFlags.None); } } } } } catch (SocketException) { Console.WriteLine(RoomName + " Drawing Thread Join"); } catch (Exception exp) { Console.WriteLine("Exception : " + exp.Message); } finally { if (listenerManager.IsListening) { listenerManager.StopListening(); } observerThread.Join(); } Console.WriteLine("$RoomServer::" + RoomName + " => Closed"); Environment.Exit(0); } else { Console.WriteLine("Server could not be verified."); } pipe.Close(); Environment.Exit(0); }
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; }