public static bool SendCommandToCore(string machine, string command) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(machine, Kernel.MBCLIENT_MUTEX_ID, PipeDirection.Out, PipeOptions.None); StreamWriter sw = new StreamWriter(pipeClient); try { pipeClient.Connect(2000); } catch (TimeoutException) { Logger.ReportWarning("Unable to send command to core (may not be running)."); return false; } try { sw.AutoFlush = true; sw.WriteLine(command); pipeClient.Flush(); pipeClient.Close(); } catch (Exception e) { Logger.ReportException("Error sending commmand to core", e); return false; } return true; }
public void Connect(string pipeName, string serverName = ".", int timeout = 2000) { NamedPipeClientStream pipeStream = null; try { pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation); pipeStream.Connect(timeout); using (var stringStream = new StringStream(pipeStream)) { if (OnConnected != null) { OnConnected(stringStream); } } } catch (Exception exception) { if (OnErrorOcurred != null) { OnErrorOcurred(exception); } } finally { if (pipeStream != null && pipeStream.IsConnected) { pipeStream.Flush(); pipeStream.Close(); } } }
static void Main() { try { using (var npcs = new NamedPipeClientStream("Stream Mosaic")) { try { npcs.Connect(500); var url = Environment.CommandLine.Substring(Environment.CommandLine.IndexOf(' ')).Trim(); var textBytes = Encoding.UTF8.GetBytes(url); npcs.Write(textBytes, 0, textBytes.Length); npcs.Flush(); var responseBytes = new byte[1]; npcs.Read(responseBytes, 0, 1); } catch (TimeoutException) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainWindow()); } } } catch (Exception exc) { MessageBox.Show(exc.ToString()); } }
static void Main() { try { using (var pipe = new NamedPipeClientStream(".", "sharp-express", PipeDirection.InOut)) { pipe.Connect(); var encoding = Encoding.UTF8; var sb = new StringBuilder(); sb.Append("GET / HTTP/1.1\r\n"); sb.Append("Header1: Hi!\r\n"); sb.Append("\r\n"); var bytes = encoding.GetBytes(sb.ToString()); pipe.Write(bytes, 0, bytes.Length); pipe.Flush(); var buf = new byte[64 * 1024]; var size = pipe.Read(buf, 0, buf.Length); var message = encoding.GetString(buf, 0, size); Console.WriteLine(message); } } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); }
// Use this for initialization void Start() { System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe"); clientStream.Connect (60); byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("Connected/n"); Debug.Log ("connected"); clientStream.Write (buffer, 0, buffer.Length); clientStream.Flush (); clientStream.Dispose (); clientStream.Close (); }
void SendToPipe() { byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("done"); System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe"); clientStream.Connect (System.TimeSpan.MaxValue.Seconds); clientStream.WaitForPipeDrain(); clientStream.Write (buffer, 0, buffer.Length); clientStream.Flush (); clientStream.Dispose(); clientStream.Close(); }
public bool Send(string pipeName, string message) { bool bSuccess = true; using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { try { pipeStream.Connect(CONNECT_TIMEOUT); pipeStream.ReadMode = PipeTransmissionMode.Message; byte[] cData = Encoding.UTF8.GetBytes(message); pipeStream.Write(cData, 0, cData.Length); pipeStream.Flush(); } catch(Exception __errExcep) { if (logger.IsErrorEnabled) logger.ErrorFormat("{0}\r\n{1}", __errExcep.Message, __errExcep.StackTrace); bSuccess = false; } } return bSuccess; }
public static void ConnectToMasterPipeAndSendData(string data) { byte[] stringData = Encoding.UTF8.GetBytes(data); int stringLength = stringData.Length; byte[] array = new byte[sizeof(Int32) + stringLength]; using (MemoryStream stream = new MemoryStream(array)) { byte[] stringLengthData = BitConverter.GetBytes(stringLength); stream.Write(stringLengthData, 0, stringLengthData.Length); stream.Write(stringData, 0, stringData.Length); } NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "SpeditNamedPipeServer", PipeDirection.Out, PipeOptions.Asynchronous); pipeClient.Connect(5000); pipeClient.Write(array, 0, array.Length); pipeClient.Flush(); pipeClient.Close(); pipeClient.Dispose(); }
public static IWebHost CreateWebHost(HttpsConnectionFilterOptions httpsOptions) { var webHostBuilder = new WebHostBuilder() .UseLoggerFactory(_loggerFactory) .UseConfiguration(Configuration) .UseKestrel(options => { if (httpsOptions != null) { options.UseHttps(httpsOptions); } //options.UseConnectionLogging(); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>(); var webHost = webHostBuilder.Build(); var serverAddresses = webHost.ServerFeatures.Get<IServerAddressesFeature>(); string pipeName = _startupOptions.WriteServerUrlsToPipe; if (pipeName != null) { NamedPipeClientStream pipe; try { pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out); pipe.Connect(10000); } catch (IOException ex) { _logger.LogCritical(0, ex, Resources.Critical_InvalidPipeHandle, pipeName); throw; } catch (TimeoutException ex) { _logger.LogCritical(0, ex, Resources.Critical_PipeConnectTimeOut, pipeName); throw; } var applicationLifetime = webHost.Services.GetService<IApplicationLifetime>(); applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => { using (pipe) { string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses); _logger.LogTrace(Resources.Trace_ServerUrlsToPipeBegin, pipeName, Environment.NewLine, serverUriStr); var serverUriData = Encoding.UTF8.GetBytes(serverUriStr); pipe.Write(serverUriData, 0, serverUriData.Length); pipe.Flush(); } _logger.LogTrace(Resources.Trace_ServerUrlsToPipeDone, pipeName); })); } return webHost; }
public static Task<bool> SendMessageAsync(object message, string pipeName, bool wait = true) { return Task.Run<bool>(new Func<bool>(() => { try { using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.None)) { using (MemoryStream ms = new MemoryStream()) { if (wait) { int i = 0; for (; i != 20; i++) { if (!NamedPipeDoesNotExist(pipeName)) break; Thread.Sleep(50); } if (i == 20) return false; } if (NamedPipeDoesNotExist(pipeName)) return false; pipeClient.Connect(10); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, message); ms.Seek(0, SeekOrigin.Begin); ms.CopyTo(pipeClient); pipeClient.Flush(); pipeClient.WaitForPipeDrain(); } } return true; } catch (Exception e) { Logging.LogException(e); return false; } })); }
public static void HandleCommandLine (int connectTimeoutMs = 2500) { var commandLineArgs = Environment.GetCommandLineArgs(); if ((commandLineArgs.Length == 3) && (commandLineArgs[1] == "--buildSolution")) { try { var jss = new JavaScriptSerializer { MaxJsonLength = 1024 * 1024 * 64 }; var pipeId = commandLineArgs[2]; using (var pipe = new NamedPipeClientStream(pipeId)) { pipe.Connect(connectTimeoutMs); using (var sr = new StreamReader(pipe)) using (var sw = new StreamWriter(pipe)) { var argsJson = sr.ReadLine(); var argsDict = jss.Deserialize<Dictionary<string, object>>(argsJson); var buildResult = Build( (string)argsDict["solutionFile"], (string)argsDict["buildConfiguration"], (string)argsDict["buildPlatform"], (string)argsDict["buildTarget"], (string)argsDict["logVerbosity"], true ); var resultJson = jss.Serialize(buildResult); sw.WriteLine(resultJson); sw.Flush(); pipe.Flush(); pipe.WaitForPipeDrain(); } } } catch (Exception exc) { Console.Error.WriteLine(exc.ToString()); Environment.Exit(1); } Environment.Exit(0); } }
public static async Task ClientPInvokeChecks() { using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.None, 4096, 4096)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Assert.False(client.CanRead); Assert.False(client.CanSeek); Assert.False(client.CanTimeout); Assert.True(client.CanWrite); Assert.False(client.IsAsync); Assert.True(client.IsConnected); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(0, client.OutBufferSize); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.True(client.OutBufferSize > 0); } else { Assert.Throws<PlatformNotSupportedException>(() => client.OutBufferSize); } Assert.Equal(PipeTransmissionMode.Byte, client.ReadMode); Assert.NotNull(client.SafePipeHandle); Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode); client.Write(new byte[] { 123 }, 0, 1); await client.WriteAsync(new byte[] { 124 }, 0, 1); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { client.WaitForPipeDrain(); } else { Assert.Throws<PlatformNotSupportedException>(() => client.WaitForPipeDrain()); } client.Flush(); await serverTask; } } using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(0, client.InBufferSize); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.True(client.InBufferSize > 0); } else { Assert.Throws<PlatformNotSupportedException>(() => client.InBufferSize); } byte[] readData = new byte[] { 0, 1 }; Assert.Equal(1, client.Read(readData, 0, 1)); Assert.Equal(1, client.ReadAsync(readData, 1, 1).Result); Assert.Equal(123, readData[0]); Assert.Equal(124, readData[1]); await serverTask; } } }
private void Send(string message) { try { if (string.IsNullOrWhiteSpace(message)) return; using (var pipeStream = new NamedPipeClientStream (".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous)) { pipeStream.Connect(Timeout*1000); var buffer = Encoding.UTF8.GetBytes(message); pipeStream.Write(buffer, 0, buffer.Length); pipeStream.Flush(); pipeStream.WaitForPipeDrain(); } } catch (Exception e) { Log.WarnFormat("An exception occurred while trying to send '{0}' to pipe '{1}': {2}", Message, PipeName, e.Message); } }
const int BUFFER_SIZE = 1024; // 1 KB #endregion Fields #region Methods static void BCLSystemIOPipeClient() { ///////////////////////////////////////////////////////////////////// // Try to open a named pipe. // // Prepare the pipe name String strServerName = "."; String strPipeName = "HelloWorld"; NamedPipeClientStream pipeClient = null; try { pipeClient = new NamedPipeClientStream( strServerName, // The server name strPipeName, // The unique pipe name PipeDirection.InOut, // The pipe is bi-directional PipeOptions.None, // No additional parameters //The server process cannot obtain identification information about //the client, and it cannot impersonate the client. TokenImpersonationLevel.Anonymous); pipeClient.Connect(60000); // set TimeOut for connection pipeClient.ReadMode = PipeTransmissionMode.Message; Console.WriteLine(@"The named pipe, \\{0}\{1}, is connected.", strServerName, strPipeName); ///////////////////////////////////////////////////////////////// // Send a message to the pipe server and receive its response. // // A byte buffer of BUFFER_SIZE bytes. The buffer should be big // enough for ONE request to the client string strMessage; byte[] bRequest; // Client -> Server int cbRequestBytes; byte[] bReply = new byte[BUFFER_SIZE]; // Server -> Client int cbBytesRead, cbReplyBytes; // Send one message to the pipe. // '\0' is appended in the end because the client may be a native // C++ program. strMessage = "Default request from client\0"; bRequest = Encoding.Unicode.GetBytes(strMessage); cbRequestBytes = bRequest.Length; if (pipeClient.CanWrite) { pipeClient.Write(bRequest, 0, cbRequestBytes); } pipeClient.Flush(); Console.WriteLine("Sends {0} bytes; Message: \"{1}\"", cbRequestBytes, strMessage.TrimEnd('\0')); // Receive one message from the pipe. cbReplyBytes = BUFFER_SIZE; do { if (pipeClient.CanRead) { cbBytesRead = pipeClient.Read(bReply, 0, cbReplyBytes); // Unicode-encode the byte array and trim all the '\0' chars // at the end. strMessage = Encoding.Unicode.GetString(bReply).TrimEnd('\0'); Console.WriteLine("Receives {0} bytes; Message: \"{1}\"", cbBytesRead, strMessage); } } while (!pipeClient.IsMessageComplete); } catch (TimeoutException ex) { Console.WriteLine("Unable to open named pipe {0}\\{1}", strServerName, strPipeName); Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine("The client throws the error: {0}", ex.Message); } finally { ///////////////////////////////////////////////////////////////// // Close the pipe. // if (pipeClient != null) pipeClient.Close(); } }
// called by post build event static void Main(string[] args) { Console.WriteLine("enter Main"); //1> Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path 'X:\jsc.svn\examples\javascript\LINQ\test\auto\TestSelect\TestSelect\bin\DebugAsServerSignal'. //1> at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) //1> at System.Threading.EventWaitHandle..ctor(Boolean initialState, EventResetMode mode, String name) //1> at AutoRefreshTestingHost.Program.Main(String[] args) in x:\jsc.svn\examples\javascript\LINQ\test\AutoRefreshTesting\AutoRefreshTestingHost\Program.cs:line 283 var AsServerSignal = new EventWaitHandle( false, EventResetMode.AutoReset, Environment.CurrentDirectory.GetHashCode() + "AsServerSignal" ); // if its a trap then start a server var AsServer = AsServerSignal.WaitOne(1); Console.WriteLine(new { AsServer } + " continue?"); if (AsServer) { //IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle; IntPtr hWnd = GetConsoleWindow(); Console.WriteLine("time to create a server?" + new { hWnd }); // are we top most? #region WindowPos.xml new Thread( delegate () { Thread.Yield(); RECT rct0; RECT rct; #region MoveWindow if (File.Exists("WindowPos.xml")) { var WindowPos = XElement.Parse(File.ReadAllText("WindowPos.xml")); MoveWindow(hWnd, (int)WindowPos.Attribute("Left"), (int)WindowPos.Attribute("Top"), (int)WindowPos.Attribute("Right") - (int)WindowPos.Attribute("Left"), (int)WindowPos.Attribute("Bottom") - (int)WindowPos.Attribute("Top"), true ); } #endregion SetWindowPos(hWnd, new IntPtr(HWND_TOPMOST), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); while (GetWindowRect(new HandleRef(null, hWnd), out rct0)) while (GetWindowRect(new HandleRef(null, hWnd), out rct)) { //Console.Write("."); //Type.mem Thread.Sleep(100); if (rct0.GetHashCode() == rct.GetHashCode()) continue; File.WriteAllText( "WindowPos.xml", new XElement( "WindowPos", new XAttribute("Left", rct.Left), new XAttribute("Top", rct.Top), new XAttribute("Right", rct.Right), new XAttribute("Bottom", rct.Bottom) ).ToString() ); //Console.WriteLine(new { X, Y, Width, Height }); break; } } ) { IsBackground = true }.Start(); #endregion var pipeServer = new NamedPipeServerStream( Environment.CurrentDirectory.GetHashCode() + "foo", PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.WriteThrough); while (true) { //Console.WriteLine("awaiting for a new connection"); pipeServer.WaitForConnection(); //Console.WriteLine("client connected to server!"); var buffer = new byte[0xffff]; var c = pipeServer.Read(buffer, 0, buffer.Length); var xml = XElement.Parse( Encoding.UTF8.GetString(buffer, 0, c) ); var old = new { Console.ForegroundColor }; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(new { xml }); Console.ForegroundColor = old.ForegroundColor; // do something with incoming params? pipeServer.Disconnect(); // server inactive for a moment, update the state and reconnect to next client InternalMain( xml.Elements().Select(x => x.Value).ToArray() ); } } var wConnected = false; new Thread( delegate () { // allow 100 until we need to take action Thread.Sleep(100); if (wConnected) { // server already active! return; } AsServerSignal.Set(); // make us a new server // cmd.exe allows us to survive a process crash. Console.WriteLine("Process.Start cmd"); Process.Start("cmd.exe", "/K " + typeof(Program).Assembly.Location); } ) { IsBackground = true }.Start(); Console.WriteLine("connecting to the server..."); var w = new NamedPipeClientStream(".", Environment.CurrentDirectory.GetHashCode() + "foo", PipeDirection.Out, PipeOptions.WriteThrough); Thread.Yield(); w.Connect(); wConnected = true; Console.WriteLine("connecting to the server... done"); // http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.jmp(v=vs.110).aspx var bytes = Encoding.UTF8.GetBytes( new XElement("xml", from x in args select new XElement("arg", x) ).ToString() ); w.Write(bytes, 0, bytes.Length); w.Flush(); w.Dispose(); //Thread.Sleep(100); //Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read. //1> at System.Console.ReadKey(Boolean intercept) //1> at System.Console.ReadKey() //Debugger.Break(); //Console.ReadKey(); }
private static void SendCommandMessage(NamedPipeClientStream pipe, String xml) { try { // Write data length (4 byte integer in big-endian byte order), xml message (string) and final null byte. _logger.LogMsg(Level.Debug, String.Format("Sending Command Response message:\r\n{0}", xml)); int data_len = xml.Length + 1; byte[] ar_bytes = BitConverter.GetBytes(data_len); //Array.Reverse(ar_bytes); // Write the length out in reverse (big-endian byte order). for (int ii = 0; ii < 4; ii++) { pipe.WriteByte(ar_bytes[3-ii]); } // Write the XML string 1 byte at a time - no nulls. Debug.WriteLine(String.Format("Writing XML to stream: total {0} chars", xml.Length.ToString())); Byte[] xml_buf = GetBytes(xml); for (int ii = 0; ii < xml_buf.Length; ii++) { if (xml_buf[ii] != 0x00) { pipe.WriteByte(xml_buf[ii]); } } // Write the final null byte that QlikView is expecting. pipe.WriteByte(0x00); // TO DO: is this Flush() necessary? pipe.Flush(); // Wait for QlikView to read from the pipe. // _logger.LogMsg(Level.Debug, "Waiting for pipe drain on command pipe."); // pipe.WaitForPipeDrain(); // _logger.LogMsg(Level.Debug, "Pipe drain complete."); } catch (System.Exception ex) { Debug.WriteLine("Error in ReadNextCommandMessage(): " + ex.Message); throw ex; } }
private static void SendDataMessage(NamedPipeClientStream pipe, String xml) { try { // Write data length, string and null _logger.LogMsg(Level.Debug, String.Format("Getting byte array from XML string for sending (data pipe).")); { // Write data length to stream. This is a 32-bit integer in big endian byte order. int data_len = xml.Length + 1; byte[] ar_bytes = BitConverter.GetBytes(data_len); for (int ii = 0; ii < 4; ii++) { pipe.WriteByte(ar_bytes[3 - ii]); } Debug.WriteLine(String.Format("Writing XML to stream: {0} chars", xml.Length.ToString())); Byte[] xml_buf = GetBytes(xml); for (int ii = 0; ii < xml_buf.Length; ii++) { if (xml_buf[ii] != 0x00) { pipe.WriteByte(xml_buf[ii]); } } Debug.WriteLine("Writing 0x00 to stream."); pipe.WriteByte(0x00); pipe.Flush(); } } catch (System.Exception ex) { Debug.WriteLine("Error in SendDateMessage(): " + ex.Message); throw ex; } }
public static void ClientPInvokeChecks() { using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Console.WriteLine("client.CanRead = {0}", client.CanRead); Console.WriteLine("client.CanSeek = {0}", client.CanSeek); Console.WriteLine("client.CanTimeout = {0}", client.CanTimeout); Console.WriteLine("client.CanWrite = {0}", client.CanWrite); Console.WriteLine("client.IsAsync = {0}", client.IsAsync); Console.WriteLine("client.IsConnected = {0}", client.IsConnected); Console.WriteLine("client.OutBufferSize = {0}", client.OutBufferSize); Console.WriteLine("client.ReadMode = {0}", client.ReadMode); Console.WriteLine("client.SafePipeHandle = {0}", client.SafePipeHandle); Console.WriteLine("client.TransmissionMode = {0}", client.TransmissionMode); client.Write(new byte[] { 123 }, 0, 1); client.WriteAsync(new byte[] { 124 }, 0, 1).Wait(); client.WaitForPipeDrain(); client.Flush(); serverTask.Wait(); } } using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Console.WriteLine("client.InBufferSize = {0}", client.InBufferSize); byte[] readData = new byte[] { 0, 1 }; client.Read(readData, 0, 1); client.ReadAsync(readData, 1, 1).Wait(); Assert.Equal(123, readData[0]); Assert.Equal(124, readData[1]); serverTask.Wait(); } } }