private async void StartInternal(CancellationToken cancellationToken) { byte[] buffer = new byte[256]; var commandBuilder = new StringBuilder(); var serverStream = new NamedPipeServerStream(this.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0); using (cancellationToken.Register(() => serverStream.Close())) { while (!cancellationToken.IsCancellationRequested) { await Task.Factory.FromAsync(serverStream.BeginWaitForConnection, serverStream.EndWaitForConnection, TaskCreationOptions.None); int read = await serverStream.ReadAsync(buffer, 0, buffer.Length); commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); while (!serverStream.IsMessageComplete) { read = serverStream.Read(buffer, 0, buffer.Length); commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); } var response = this.HandleReceivedCommand(commandBuilder.ToString()); var responseBytes = Encoding.ASCII.GetBytes(response); serverStream.Write(responseBytes, 0, responseBytes.Length); serverStream.WaitForPipeDrain(); serverStream.Disconnect(); commandBuilder.Clear(); } } }
public static void ServerSendsByteClientReceives() { using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { byte[] sent = new byte[] { 123 }; byte[] received = new byte[] { 0 }; Task t = Task.Run(() => { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In)) { client.Connect(); Assert.True(client.IsConnected); int bytesReceived = client.Read(received, 0, 1); Assert.Equal(1, bytesReceived); } }); server.WaitForConnection(); Assert.True(server.IsConnected); server.Write(sent, 0, 1); t.Wait(); Assert.Equal(sent[0], received[0]); } }
private void startServer(object state) { try { var pipe = state.ToString(); using (var server = new NamedPipeServerStream(pipe, PipeDirection.Out)) { server.WaitForConnection(); while (server.IsConnected) { if (_messages.Count == 0) { Thread.Sleep(100); continue; } var bytes = _messages.Pop(); var buffer = new byte[bytes.Length + 1]; Array.Copy(bytes, buffer, bytes.Length); buffer[buffer.Length - 1] = 0; server.Write(buffer, 0, buffer.Length); } } } catch { } }
using (NamedPipeServerStream serverPipeStream = new NamedPipeServerStream("SamplePipe")) { Console.WriteLine("Waiting for client to connect."); serverPipeStream.WaitForConnection(); Console.WriteLine("Connected to client."); byte[] bytes = Encoding.UTF8.GetBytes("Hello World\n"); while (true) { serverPipeStream.Write(bytes, 0, bytes.Length); serverPipeStream.Flush(); //to get sure it is send immediatelly Thread.Sleep(1000); } } } } }
static void Main(string[] args) { // *** SERVIDOR UTF8Encoding encoding = new UTF8Encoding(); using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("CS3", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None)) { pipeStream.WaitForConnection(); // envío de mensajes for (int i = 0; i < 100; i++) { string msg = i.ToString(); byte[] bytes = encoding.GetBytes(msg); pipeStream.Write(bytes, 0, bytes.Length); } } }
static void Test2() { NamedPipeServerStream stream = new NamedPipeServerStream("MaxUnityBridge"); stream.WaitForConnection(); do { byte[] data = new byte[4]; stream.Read(data, 0, 4); System.Console.WriteLine(string.Format("Received: {0} {1} {2} {3}", data[0], data[1], data[2], data[3])); stream.Write(new byte[] { 5, 6, 7, 8 }, 0, 4); System.Console.WriteLine("Sent: 5 6 7 8"); stream.Flush(); stream.WaitForPipeDrain(); } while (true); }
public static async Task ServerPInvokeChecks() { // calling every API related to server and client to detect any bad PInvokes using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { Task clientTask = Task.Run(() => StartClient(PipeDirection.In)); server.WaitForConnection(); Assert.False(server.CanRead); Assert.False(server.CanSeek); Assert.False(server.CanTimeout); Assert.True(server.CanWrite); Assert.False(server.IsAsync); Assert.True(server.IsConnected); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(0, server.OutBufferSize); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.True(server.OutBufferSize > 0); } else { Assert.Throws<PlatformNotSupportedException>(() => server.OutBufferSize); } Assert.Equal(PipeTransmissionMode.Byte, server.ReadMode); Assert.NotNull(server.SafePipeHandle); Assert.Equal(PipeTransmissionMode.Byte, server.TransmissionMode); server.Write(new byte[] { 123 }, 0, 1); await server.WriteAsync(new byte[] { 124 }, 0, 1); server.Flush(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { server.WaitForPipeDrain(); } else { Assert.Throws<PlatformNotSupportedException>(() => server.WaitForPipeDrain()); } await clientTask; } using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In)) { Task clientTask = Task.Run(() => StartClient(PipeDirection.Out)); server.WaitForConnection(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(0, server.InBufferSize); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.True(server.InBufferSize > 0); } else { Assert.Throws<PlatformNotSupportedException>(() => server.InBufferSize); } byte[] readData = new byte[] { 0, 1 }; Assert.Equal(1, server.Read(readData, 0, 1)); Assert.Equal(1, server.ReadAsync(readData, 1, 1).Result); Assert.Equal(123, readData[0]); Assert.Equal(124, readData[1]); } }
/// <summary> /// Creates a new named pipe from a Youtube video link. /// </summary> /// <param name="source">Source stream.</param> /// <param name="namedPipeName">Named pipe.</param> /// <param name="onProgress">Function executed when progress changes. Return true to cancel the operation, false to continue.</param> /// <param name="onFinish">Action executed when a reading operation finishes.</param> /// <returns>Pipe name.</returns> public static string NamedPipeFromStreamAsync(this Stream source, string namedPipeName, Func<float, bool> onProgress = null, Action onFinish = null) { if (source == null) new ArgumentNullException(nameof(source)); Task.Factory.StartNew(() => { using (NamedPipeServerStream target = new NamedPipeServerStream(namedPipeName)) { target.WaitForConnection(); target.WaitForPipeDrain(); int bytes, copiedBytes = 0; var buffer = new byte[1024]; while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0) { target.Write(buffer, 0, bytes); copiedBytes += bytes; if (onProgress != null) { bool shouldCancel = onProgress((float)copiedBytes / source.Length); if (shouldCancel) break; } } target.Flush(); if (onFinish != null) onFinish(); } }); return namedPipeName; }
/// <summary> /// Use the pipe classes in the System.IO.Pipes namespace to create the /// named pipe. This solution is recommended. /// </summary> public static void Run() { NamedPipeServerStream pipeServer = null; try { // Prepare the security attributes (the pipeSecurity parameter in // the constructor of NamedPipeServerStream) for the pipe. This // is optional. If pipeSecurity of NamedPipeServerStream is null, // the named pipe gets a default security descriptor.and the // handle cannot be inherited. The ACLs in the default security // descriptor of a pipe grant full control to the LocalSystem // account, (elevated) administrators, and the creator owner. // They also give only read access to members of the Everyone // group and the anonymous account. However, if you want to // customize the security permission of the pipe, (e.g. to allow // Authenticated Users to read from and write to the pipe), you // need to create a PipeSecurity object. PipeSecurity pipeSecurity = null; pipeSecurity = CreateSystemIOPipeSecurity(); // Create the named pipe. pipeServer = new NamedPipeServerStream( Program.PipeName, // The unique pipe name. PipeDirection.InOut, // The pipe is duplex NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // Message-based communication PipeOptions.None, // No additional parameters Program.BufferSize, // Input buffer size Program.BufferSize, // Output buffer size pipeSecurity, // Pipe security attributes HandleInheritability.None // Not inheritable ); Console.WriteLine("The named pipe ({0}) is created.", Program.FullPipeName); // Wait for the client to connect. Console.WriteLine("Waiting for the client's connection..."); pipeServer.WaitForConnection(); Console.WriteLine("Client is connected."); // // Receive a request from client. // // Note: The named pipe was created to support message-based // communication. This allows a reading process to read // varying-length messages precisely as sent by the writing // process. In this mode you should not use StreamWriter to write // the pipe, or use StreamReader to read the pipe. You can read // more about the difference from the article: // http://go.microsoft.com/?linkid=9721786. // string message; do { byte[] bRequest = new byte[Program.BufferSize]; int cbRequest = bRequest.Length, cbRead; cbRead = pipeServer.Read(bRequest, 0, cbRequest); // Unicode-encode the received byte array and trim all the // '\0' characters at the end. message = Encoding.Unicode.GetString(bRequest).TrimEnd('\0'); Console.WriteLine("Receive {0} bytes from client: \"{1}\"", cbRead, message); } while (!pipeServer.IsMessageComplete); // // Send a response from server to client. // var proc = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = message, Arguments = "", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); StringBuilder sb = new StringBuilder(); while (!proc.StandardOutput.EndOfStream) { string line = proc.StandardOutput.ReadLine(); // do something with line sb.Append("\n" + line ); } //System.Diagnostics.Process.Start(message); sb.Append("###AAA###" + proc.ExitCode + "###BBB###"); message = sb.ToString(); //System.Diagnostics.Process.Start("notepad"); byte[] bResponse = Encoding.Unicode.GetBytes(message); int cbResponse = bResponse.Length; pipeServer.Write(bResponse, 0, cbResponse); // Console.WriteLine("Send {0} bytes to client: \"{1}\"", // cbResponse, message.TrimEnd('\0')); // Flush the pipe to allow the client to read the pipe's contents // before disconnecting. Then disconnect the client's connection. pipeServer.WaitForPipeDrain(); pipeServer.Disconnect(); } catch (Exception ex) { Console.WriteLine("The server throws the error: {0}", ex.Message); } finally { if (pipeServer != null) { pipeServer.Close(); pipeServer = null; } } }
// tmrDraw is a timer that 'ticks' once every 5 milliseconds. Upon a 'tick', we check to see // if there is enough new data from the USB port to update our waveform plots. private void tmrDraw_Tick(object sender, EventArgs e) { if (readMode == true) { // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); // DateTime d1 = DateTime.Now; if (plotQueue.Count > 0) { // lblStatus.Text = "plotQueue.Count = " + plotQueue.Count.ToString(); USBData plotData; plotData = plotQueue.Dequeue(); plotQueue.Clear(); plotData.CopyToArray(dataFrame, auxFrame); /*matlab if (checkBox2.Checked) { matlab.PutWorkspaceData("b", "base", dataFrame); } //matlab.PutWorkspaceData("c", "base", x); //Console.WriteLine(matlab.Execute("d(c) = b")); */ if (spikeWindowVisible) { if (mySpikeRecord.FindSpikes(dataFrame) > 0) { frmMagnifyForm.DrawSpikes(); } } // DateTime dt = DateTime.Now; if (saveMode) { lblStatus.Text = String.Concat("Saving data to file ", saveFileName, ". Estimated file size = ", fileSize.ToString("F01"), " MB."); } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); float y_offset; Rectangle rectBounds; // Which channels should we plot on the screen? displayChannel[0] = chkChannel1.Checked; displayChannel[1] = chkChannel2.Checked; displayChannel[2] = chkChannel3.Checked; displayChannel[3] = chkChannel4.Checked; displayChannel[4] = chkChannel5.Checked; displayChannel[5] = chkChannel6.Checked; displayChannel[6] = chkChannel7.Checked; displayChannel[7] = chkChannel8.Checked; displayChannel[8] = chkChannel9.Checked; displayChannel[9] = chkChannel10.Checked; displayChannel[10] = chkChannel11.Checked; displayChannel[11] = chkChannel12.Checked; displayChannel[12] = chkChannel13.Checked; displayChannel[13] = chkChannel14.Checked; displayChannel[14] = chkChannel15.Checked; displayChannel[15] = chkChannel16.Checked; float yPlotScale = YScaleFactors[yScaleIndex]; if (xScaleIndex == 0) { rectBounds = new Rectangle(XPlotOffset, 0, 751, 800); myBuffer.Graphics.FillRectangle(SystemBrushes.Control, rectBounds); // Plot amplifier waveforms on screen for (int channel = 0; channel < 16; channel++) { if (displayChannel[channel] == true) { y_offset = (float)channel * -40.0F + 582.0F; for (int x = 1; x < 750; x++) { //matlab if (channel == 1) { //matlab.PutWorkspaceData("b", "base", dataFrame[channel, x]); //matlab.PutWorkspaceData("c", "base", x); //Console.WriteLine(matlab.Execute("d(c) = b")); } if (spikeWindowVisible == true && channel == mySpikeRecord.Channel) { myBuffer.Graphics.DrawLine(Pens.Blue, (float)x + (float)XPlotOffset, 640.0F - (y_offset + yPlotScale * dataFrame[channel, x - 1]), (float)x + (float)XPlotOffset + 1.0F, 640.0F - (y_offset + yPlotScale * dataFrame[channel, x])); } else { myBuffer.Graphics.DrawLine(Pens.Black, (float)x + (float)XPlotOffset, 640.0F - (y_offset + yPlotScale * dataFrame[channel, x - 1]), (float)x + (float)XPlotOffset + 1.0F, 640.0F - (y_offset + yPlotScale * dataFrame[channel, x])); } } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); } } // Plot Port J3 auxiliary TTL input rasters on screen for (int aux = 0; aux < 6; aux++) { y_offset = 698.0F + 3.0F * (float)aux; for (int x = 1; x < 750; x++) { if ((auxFrame[x - 1] & (UInt16)(1 << aux)) > 0) { myBuffer.Graphics.DrawLine(auxPens[aux], (float)x + (float)XPlotOffset, y_offset, (float)x + (float)XPlotOffset + 1.0F, y_offset); } } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); } } else { int drawWidth, dataChunk; switch (xScaleIndex) { case 1: drawWidth = 250; break; case 2: drawWidth = 150; break; case 3: drawWidth = 75; break; case 4: drawWidth = 30; break; case 5: drawWidth = 15; break; case 6: drawWidth = 5; break; default: drawWidth = 5; break; } dataChunk = 750 / drawWidth; float maxValue, minValue; bool auxHigh; rectBounds = new Rectangle(xSlowPos + XPlotOffset, 0, drawWidth, 800); myBuffer.Graphics.FillRectangle(SystemBrushes.Control, rectBounds); if (xSlowPos == 0) { rectBounds = new Rectangle(750 + XPlotOffset, 0, 1, 800); myBuffer.Graphics.FillRectangle(SystemBrushes.Control, rectBounds); } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); for (int x1 = 0; x1 < drawWidth; x1++) { // Plot amplifier waveforms on screen for (int channel = 0; channel < 16; channel++) { if (displayChannel[channel] == true) { maxValue = -999999.0F; minValue = 999999.0F; for (int x2 = 0; x2 < dataChunk; x2++) { if (dataFrame[channel, dataChunk * x1 + x2] > maxValue) { maxValue = dataFrame[channel, dataChunk * x1 + x2]; } if (dataFrame[channel, dataChunk * x1 + x2] < minValue) { minValue = dataFrame[channel, dataChunk * x1 + x2]; } } y_offset = (float)channel * -40.0F + 582.0F; // DrawLine will not draw anything if the specified line is too short, so we must set a // lower bound on its length. if (yPlotScale * (maxValue - minValue) < 0.10F) { maxValue += 0.1F / yPlotScale; } if (spikeWindowVisible == true && channel == mySpikeRecord.Channel) { myBuffer.Graphics.DrawLine(Pens.Blue, (float)xSlowPos + (float)XPlotOffset, 640.0F - (y_offset + yPlotScale * minValue), (float)xSlowPos + (float)XPlotOffset, 640.0F - (y_offset + yPlotScale * maxValue)); } else { myBuffer.Graphics.DrawLine(Pens.Black, (float)xSlowPos + (float)XPlotOffset, 640.0F - (y_offset + yPlotScale * minValue), (float)xSlowPos + (float)XPlotOffset, 640.0F - (y_offset + yPlotScale * maxValue)); } } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); } // Plot Port J3 auxiliary TTL input rasters on screen for (int aux = 0; aux < 6; aux++) { y_offset = 698.0F + 3.0F * (float)aux; auxHigh = false; for (int x2 = 0; x2 < dataChunk; x2++) { if ((auxFrame[dataChunk * x1 + x2] & (UInt16)(1 << aux)) > 0) { auxHigh = true; x2 = dataChunk; } } if (auxHigh) { myBuffer.Graphics.DrawLine(auxPens[aux], (float)xSlowPos + (float)XPlotOffset, y_offset, (float)xSlowPos + (float)XPlotOffset, y_offset + 0.1F); } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); } xSlowPos++; } if (xScaleIndex > 2) { myBuffer.Graphics.DrawLine(Pens.Red, xSlowPos + XPlotOffset, 0, xSlowPos + XPlotOffset, 800); // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); } if (xSlowPos >= 750) xSlowPos = 0; } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); myBuffer.Render(); // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); } // DateTime d2 = DateTime.Now; // double elapsedTimeMSec = ((TimeSpan)(d2 - d1)).TotalMilliseconds; // lblStatus.Text = "frame rate (in msec): " + elapsedTimeMSec.ToString(); // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); // If we are in Record mode, save selected data to disk if (saveMode == true) { USBData saveData; while (saveQueue.Count > 0) { saveData = saveQueue.Dequeue(); saveData.CopyToArray(dataFrame, auxFrame); for (int i = 0; i < 750; i++) { if (chkChannel1.Checked) binWriter.Write(dataFrame[0, i]); if (chkChannel2.Checked) binWriter.Write(dataFrame[1, i]); if (chkChannel3.Checked) binWriter.Write(dataFrame[2, i]); if (chkChannel4.Checked) binWriter.Write(dataFrame[3, i]); if (chkChannel5.Checked) binWriter.Write(dataFrame[4, i]); if (chkChannel6.Checked) binWriter.Write(dataFrame[5, i]); if (chkChannel7.Checked) binWriter.Write(dataFrame[6, i]); if (chkChannel8.Checked) binWriter.Write(dataFrame[7, i]); if (chkChannel9.Checked) binWriter.Write(dataFrame[8, i]); if (chkChannel10.Checked) binWriter.Write(dataFrame[9, i]); if (chkChannel11.Checked) binWriter.Write(dataFrame[10, i]); if (chkChannel12.Checked) binWriter.Write(dataFrame[11, i]); if (chkChannel13.Checked) binWriter.Write(dataFrame[12, i]); if (chkChannel14.Checked) binWriter.Write(dataFrame[13, i]); if (chkChannel15.Checked) binWriter.Write(dataFrame[14, i]); if (chkChannel16.Checked) binWriter.Write(dataFrame[15, i]); binWriter.Write((byte)auxFrame[i]); } fileSize += (750.0 * 1.0) / 1000000.0; // aux inputs for (int channel = 0; channel < 16; channel++) { if (displayChannel[channel]) fileSize += (750.0 * 4.0) / 1000000.0; } fileSaveTime += 750.0 / 25000.0; if (fileSaveTime >= ((double)numMaxMinutes.Value)) // Every X minutes, close existing file and start a new one { if (SaveCheckBox.Checked) { binWriter.Flush(); binWriter.Close(); fs.Close(); DateTime dt = DateTime.Now; saveFileName = String.Concat(Path.GetDirectoryName(saveFileDialog1.FileName), Path.DirectorySeparatorChar, Path.GetFileNameWithoutExtension(saveFileDialog1.FileName), dt.ToString("_yyMMdd_HHmmss"), ".int"); fs = new FileStream(saveFileName, FileMode.Create); binWriter = new BinaryWriter(fs); fileSize = 0.0; fileSaveTime = 0.0; if (checkBox1.Checked) { Console.WriteLine("Waiting for connection on named pipe mypipe"); System.IO.Pipes.NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream("mypipe"); namedPipeServerStream.WaitForConnection(); string line = "f**k"; //float lll = dataFrame[1, 1]; byte[] buffer = ASCIIEncoding.ASCII.GetBytes(line); namedPipeServerStream.Write(buffer, 0, buffer.Length); namedPipeServerStream.Close(); } if (checkBox2.Checked) { } binWriter.Write((byte)128); binWriter.Write((byte)1); binWriter.Write((byte)1); for (int channel = 0; channel < 16; channel++) { if (displayChannel[channel] == true) binWriter.Write((byte)1); else binWriter.Write((byte)0); } for (int i = 0; i < 48; i++) binWriter.Write((byte)0); } else { binWriter.Flush(); readMode = false; if (serialPort1.IsOpen) serialPort1.WriteLine("0"); btnZCheck.ForeColor = SystemColors.ControlText; myUSBSource.Stop(); binWriter.Close(); fs.Close(); saveMode = false; chkChannel1.Enabled = true; chkChannel2.Enabled = true; chkChannel3.Enabled = true; chkChannel4.Enabled = true; chkChannel5.Enabled = true; chkChannel6.Enabled = true; chkChannel7.Enabled = true; chkChannel8.Enabled = true; chkChannel9.Enabled = true; chkChannel10.Enabled = true; chkChannel11.Enabled = true; chkChannel12.Enabled = true; chkChannel13.Enabled = true; chkChannel14.Enabled = true; chkChannel15.Enabled = true; chkChannel16.Enabled = true; lblStatus.Text = "Ready to start."; } } } } else { saveQueue.Clear(); } // Must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow. myUSBSource.CheckForUsbData(plotQueue, saveQueue); } }
public FakeSerialPort(string portName) { _baseStream = new ByteStream(portName); _baseStream.iowBS.PropertyChanged += new PropertyChangedEventHandler(_baseStream_PropertyChanged); NamedPipeServerStream npss = new NamedPipeServerStream("PipeStream1", PipeDirection.Out); Process pr = Process.Start(@"C:\Users\Jim\Documents\GitHub\CCI_project\SerialPortIO\bin\Debug\SerialPortIO.exe", portName); npss.WaitForConnection(); byte[] b = { 0x43, 0x4F, 0x4D, 0x31 }; npss.Write(b, 0, 4); }
//private const int ALLSELECT = 60; //private const int CUT = 52; static void Main(string[] args) { string[] simpleNames = { "Yukari", "Maki", "Zunko", "Akane", "Aoi", "Koh" }; string[] voiceroidNames = { "VOICEROID+ 結月ゆかり EX", "VOICEROID+ 民安ともえ EX", "VOICEROID+ 東北ずん子 EX", "VOICEROID+ 琴葉茜", "VOICEROID+ 琴葉葵", "VOICEROID+ 水奈瀬コウ EX" }; Console.WriteLine(""); //引数のチェック if (args.Length < 1) { string mergeName = ""; for (int i = 0; i < simpleNames.Length; i++) { mergeName = mergeName + simpleNames[i]; if (i < simpleNames.Length - 1) mergeName = mergeName + ", "; } Console.WriteLine("使用するVOICEROIDを引数に追加してください: " + mergeName); return; } //引数に設定されたボイスロイドの名前をチェック string selectedSimple = null; int selectedIndex = 0; for (int i = 0; i < simpleNames.Length; i++) { if (args[0].CompareTo(simpleNames[i]) == 0) { selectedSimple = simpleNames[i]; selectedIndex = i; break; } } if (selectedSimple == null) { string mergeName = ""; for (int i = 0; i < simpleNames.Length; i++) { mergeName = mergeName + simpleNames[i]; if (i < simpleNames.Length - 1) mergeName = mergeName + ", "; } Console.WriteLine("引数に指定されたVOICEROIDの名前が正しくありません. 使用できる名前は次のとおりです: " + mergeName); return; } //VOICEROID.exeの起動チェック Process[] apps = Process.GetProcessesByName("VOICEROID"); if (apps.Length < 1) { Console.WriteLine("プロセスに" + voiceroidNames[selectedIndex] + "のVOICEROID.exeがありません. " + voiceroidNames[selectedIndex] + "を起動してください."); return; } //VOICEROID.exeのプロセス取得 AutomationElement ae = null; foreach (Process app in apps) { AutomationElement rootHandle = AutomationElement.FromHandle(app.MainWindowHandle); foreach(string voiceroidName in voiceroidNames) { string name = rootHandle.Current.Name; if (name.CompareTo(voiceroidNames[selectedIndex]) == 0 || name.CompareTo(voiceroidNames[selectedIndex]+"*") == 0) ae = rootHandle; } } //起動しているVOICEROID.exeと指定されたキャラクターのVOICEROID.exeが一致しなかった時 if(ae == null) { string mergeName = ""; for (int i = 0; i < simpleNames.Length; i++) { mergeName = mergeName + simpleNames[i]; if (i < simpleNames.Length - 1) mergeName = mergeName + ", "; } Console.WriteLine("引数に指定された名前のVOICEROIDが起動していません. 他の名前を指定するか, 指定した名前のVOICEROID.exeを起動してください: " + mergeName); return; } Console.Clear(); //ウィンドウにフォーカスをあわせる ae.SetFocus(); //テキストボックス、再生ボタン、停止ボタンのGUIコントロール取得 AutomationElement txtForm = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtMain", PropertyConditionFlags.IgnoreCase)); IntPtr txtFormHandle = IntPtr.Zero; try { txtFormHandle = (IntPtr)txtForm.Current.NativeWindowHandle; } catch (NullReferenceException e) { //ハンドルが取得できなかった場合、ウィンドウが見つかっていない Console.WriteLine(voiceroidNames[selectedIndex] + "のウィンドウが取得できませんでした. 最小化されているか, ほかのプロセスによってブロックされています."); return; } //テキストボックスのハンドルを取得 IntPtr txtControl = FindWindowEx(txtFormHandle, IntPtr.Zero, null, null); //再生ボタンのハンドルを取得 AutomationElement btnPlay = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "btnPlay", PropertyConditionFlags.IgnoreCase)); IntPtr btnControl = (IntPtr)btnPlay.Current.NativeWindowHandle; //停止ボタンのハンドルを取得 AutomationElement btnStop = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "btnStop", PropertyConditionFlags.IgnoreCase)); IntPtr stpControl = (IntPtr)btnStop.Current.NativeWindowHandle; //音量、速度、高さ、抑揚のテキストボックスのコントロールを取得 AutomationElement txtVol = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtVolume", PropertyConditionFlags.IgnoreCase)); AutomationElement txtSpd = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtSpeed", PropertyConditionFlags.IgnoreCase)); AutomationElement txtPit = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtPitch", PropertyConditionFlags.IgnoreCase)); AutomationElement txtEmp = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtEmphasis", PropertyConditionFlags.IgnoreCase)); //音声効果の画面が表示されていない時の処理 if (txtVol == null || txtSpd == null || txtPit == null || txtEmp == null) { Console.WriteLine("音声効果の画面を展開しています..."); Thread.Sleep(100); //音声チューニングのタブを取得 AutomationElementCollection tabs = ae.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "タブ項目", PropertyConditionFlags.IgnoreCase)); //音声チューニングのタブが取得できない時の処理 if (tabs.Count < 1) { AutomationElementCollection menues = ae.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "メニュー項目", PropertyConditionFlags.IgnoreCase)); //音声チューニングのウィンドウを表示する foreach (AutomationElement menu in menues) { if (menu.Current.Name.CompareTo("音声チューニング(T)") == 0) { object ipShowTuning; if (menu.TryGetCurrentPattern(InvokePattern.Pattern, out ipShowTuning)) { ((InvokePattern)ipShowTuning).Invoke(); Thread.Sleep(1000); } } } //再度音声チューニング tabs = ae.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "タブ項目", PropertyConditionFlags.IgnoreCase)); } //音声効果のタブを探す foreach (AutomationElement tab in tabs) { if (tab.Current.Name.CompareTo("音声効果") == 0) { object ipShowSoundEffect; if (tab.TryGetCurrentPattern(SelectionItemPattern.Pattern, out ipShowSoundEffect)) { ((SelectionItemPattern)ipShowSoundEffect).Select(); Thread.Sleep(1000); } } } //再度、音量、速度、高さ、抑揚のテキストボックスのコントロールを取得 txtVol = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtVolume", PropertyConditionFlags.IgnoreCase)); txtSpd = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtSpeed", PropertyConditionFlags.IgnoreCase)); txtPit = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtPitch", PropertyConditionFlags.IgnoreCase)); txtEmp = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtEmphasis", PropertyConditionFlags.IgnoreCase)); } //再度、音量、速度、高さ、抑揚のハンドルを取得 IntPtr txtVolControl = (IntPtr)txtVol.Current.NativeWindowHandle; IntPtr txtSpdControl = (IntPtr)txtSpd.Current.NativeWindowHandle; IntPtr txtPitControl = (IntPtr)txtPit.Current.NativeWindowHandle; IntPtr txtEmpControl = (IntPtr)txtEmp.Current.NativeWindowHandle; //InvokePattern ipBtnPlay = (InvokePattern)btnPlay.GetCurrentPattern(InvokePattern.Pattern); //ValuePattern vpTxtVol = (ValuePattern)txtVol.GetCurrentPattern(ValuePattern.Pattern); //ValuePattern vpTxtSpd = (ValuePattern)txtSpd.GetCurrentPattern(ValuePattern.Pattern); //ValuePattern vpTxtPit = (ValuePattern)txtPit.GetCurrentPattern(ValuePattern.Pattern); //ValuePattern vpTxtEmp = (ValuePattern)txtEmp.GetCurrentPattern(ValuePattern.Pattern); string btnName = btnPlay.Current.Name; string message = ""; Console.WriteLine("[voiceroid_talker" +selectedSimple + "]のサーバーを開始しています..."); //メインループ while (true) { string clientMessage; string[] messages; string messageVol = "1.0"; string messageSpd = "1.0"; string messagePit = "1.0"; string messageEmp = "1.0"; //通信セッションの開始 try { using (NamedPipeServerStream server = new NamedPipeServerStream("voiceroid_talker" + selectedSimple)) { Console.WriteLine("クライアントからのメッセージを待っています..."); server.WaitForConnection(); byte[] buffer = new byte[1024]; server.Read(buffer, 0, buffer.Length); string messageRaw = UnicodeEncoding.Unicode.GetString(buffer); clientMessage = messageRaw.Trim('\0'); //通信メッセージの内容をパースする messages = clientMessage.Split(';'); if (messages.Length == 1) { message = clientMessage; if (message.CompareTo("exit") == 0) break; } else { message = messages[0]; } //音量のパラメータを取得する if (messages.Length >= 2) { float val = 0.0f; if (float.TryParse(messages[1], out val)) messageVol = val.ToString(); } //速度のパラメータを取得する if (messages.Length >= 3) { float val = 0.0f; if (float.TryParse(messages[2], out val)) messageSpd = val.ToString(); } //高さのパラメータを取得する if (messages.Length >= 4) { float val = 0.0f; if (float.TryParse(messages[3], out val)) messagePit = val.ToString(); } //抑揚のパラメータを取得する if (messages.Length >= 5) { float val = 0.0f; if (float.TryParse(messages[4], out val)) messageEmp = val.ToString(); } //音量、速度、高さ、抑揚のテキストボックスに値を入力 SendMessage(txtVolControl, WM_SETTEXT, IntPtr.Zero, messageVol); PostMessage(txtVolControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null); SendMessage(txtSpdControl, WM_SETTEXT, IntPtr.Zero, messageSpd); PostMessage(txtSpdControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null); SendMessage(txtPitControl, WM_SETTEXT, IntPtr.Zero, messagePit); PostMessage(txtPitControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null); SendMessage(txtEmpControl, WM_SETTEXT, IntPtr.Zero, messageEmp); PostMessage(txtEmpControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null); Thread.Sleep(10); //テキストボックスにメッセージを入れ、再生する SendMessage(txtControl, WM_SETTEXT, IntPtr.Zero, message); PostMessage(stpControl, WM_CLICK, IntPtr.Zero, null); PostMessage(btnControl, WM_CLICK, IntPtr.Zero, null); //ipBtnPlay.Invoke(); Thread.Sleep(100); //レスポンス用メッセージをクライアントに送信 byte[] response = UnicodeEncoding.Unicode.GetBytes("OK"); server.Write(response, 0, 2); //セッションを終了する server.Close(); } } catch(IOException e) { //セッション作成時にエラーが発生した場合 Console.WriteLine("通信セッションの作成に失敗しました. 他のサーバーによって, 同名のセッションが開始されている可能性があります."); break; } } }
const int BUFFER_SIZE = 4096; // 4 KB #endregion Fields #region Methods /// <summary> /// Named pipe server through BCL System.IO.Pipes /// </summary> static void BCLSystemIOPipeServer() { NamedPipeServerStream pipeServer = null; try { ///////////////////////////////////////////////////////////////// // Create a named pipe. // // Prepare the pipe name String strPipeName = "HelloWorld"; // Prepare the security attributes // Granting everyone the full control of the pipe is just for // demo purpose, though it creates a security hole. PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); // Create the named pipe pipeServer = new NamedPipeServerStream( strPipeName, // The unique pipe name. PipeDirection.InOut, // The pipe is bi-directional NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // Message type pipe PipeOptions.None, // No additional parameters BUFFER_SIZE, // Input buffer size BUFFER_SIZE, // Output buffer size pipeSa, // Pipe security attributes HandleInheritability.None // Not inheritable ); Console.WriteLine("The named pipe, {0}, is created", strPipeName); ///////////////////////////////////////////////////////////////// // Wait for the client to connect. // Console.WriteLine("Waiting for the client's connection..."); pipeServer.WaitForConnection(); ///////////////////////////////////////////////////////////////// // Read client requests from the pipe and write the response. // // A byte buffer of BUFFER_SIZE bytes. The buffer should be big // enough for ONE request from a client. string strMessage; byte[] bRequest = new byte[BUFFER_SIZE];// Client -> Server int cbBytesRead, cbRequestBytes; byte[] bReply; // Server -> Client int cbBytesWritten, cbReplyBytes; do { // Receive one message from the pipe. cbRequestBytes = BUFFER_SIZE; cbBytesRead = pipeServer.Read(bRequest, 0, cbRequestBytes); // Unicode-encode the byte array and trim all the '\0' chars // at the end. strMessage = Encoding.Unicode.GetString(bRequest).TrimEnd('\0'); Console.WriteLine("Receives {0} bytes; Message: \"{1}\"", cbBytesRead, strMessage); // Prepare the response. // '\0' is appended in the end because the client may be a // native C++ program. strMessage = "Default response from server\0"; bReply = Encoding.Unicode.GetBytes(strMessage); cbReplyBytes = bReply.Length; // Write the response to the pipe. pipeServer.Write(bReply, 0, cbReplyBytes); // If no IO exception is thrown from Write, number of bytes // written (cbBytesWritten) != -1. cbBytesWritten = cbReplyBytes; Console.WriteLine("Replies {0} bytes; Message: \"{1}\"", cbBytesWritten, strMessage.TrimEnd('\0')); } while (!pipeServer.IsMessageComplete); ///////////////////////////////////////////////////////////////// // Flush the pipe to allow the client to read the pipe's contents // before disconnecting. Then disconnect the pipe. // pipeServer.Flush(); pipeServer.Disconnect(); } catch (Exception ex) { Console.WriteLine("The server throws the error: {0}", ex.Message); } finally { if (pipeServer != null) { // Close the stream. pipeServer.Close(); } } }
static void SendUnityPipe(NamedPipeServerStream server, string data) { byte[] msg = Encoding.ASCII.GetBytes(data); // convert to byte //WRITE TO PIPE server.Write(msg, 0, msg.Length); //foreach (var item in msg) //{ // Console.WriteLine("Wrote: {0}", item.ToString()); //} }
private void WriteSecretToPipe(NamedPipeServerStream pipe, string secret) { byte[] buffer = Encoding.Unicode.GetBytes(secret); WriteNumberToPipe(pipe, (uint)buffer.Length); pipe.Write(buffer, 0, buffer.Length); }
private void MessageServer() { using (var s = new NamedPipeServerStream("x-pipedream", PipeDirection.InOut, 1, PipeTransmissionMode.Message)) { s.WaitForConnection(); connected = true; while (true) { var msg = Encoding.UTF8.GetBytes("Hello" + i++); s.Write(msg, 0, msg.Length); //blocks until read? } } }
public static void ClientCloneTests() { const string pipeName = "fooClientclone"; byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] received0 = new byte[] { }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte)) { using (NamedPipeClientStream clientBase = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None)) { Task clientTask = Task.Run(() => { clientBase.Connect(); using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.InOut, false, true, clientBase.SafePipeHandle)) { client.Write(msg1, 0, msg1.Length); int serverCount = client.NumberOfServerInstances; Assert.Equal(1, serverCount); Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode); } }); server.WaitForConnection(); int len1 = server.Read(received1, 0, msg1.Length); Assert.Equal(msg1.Length, len1); Assert.Equal(msg1, received1); // test special cases of buffer lengths = 0 int len0 = server.Read(received0, 0, 0); Assert.Equal(0, len0); server.Write(received0, 0, 0); Task<int> serverTaskRead = server.ReadAsync(received0, 0, 0); serverTaskRead.Wait(); Assert.Equal(0, serverTaskRead.Result); server.WriteAsync(received0, 0, 0).Wait(); } } }
public bool StartServer(string strEventName, string strPipeName, Action<CMD_STREAM, CMD_STREAM> pfnCmdProc) { if (pfnCmdProc == null || strEventName.Length == 0 || strPipeName.Length == 0) { return false; } if (m_ServerThread != null) { return false; } m_StopFlag = false; m_PulseEvent = new AutoResetEvent(false); m_ServerThread = new Thread(new ThreadStart(() => { using (EventWaitHandle eventConnect = new EventWaitHandle(false, EventResetMode.AutoReset, strEventName)) using (NamedPipeServerStream pipe = new NamedPipeServerStream( strPipeName.Substring(strPipeName.StartsWith("\\\\.\\pipe\\", StringComparison.OrdinalIgnoreCase) ? 9 : 0), PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { while (m_StopFlag == false) { pipe.BeginWaitForConnection(asyncResult => { try { if (m_StopFlag == false) { pipe.EndWaitForConnection(asyncResult); m_PulseEvent.Set(); } } catch (ObjectDisposedException) { } }, null); eventConnect.Set(); m_PulseEvent.WaitOne(); if (pipe.IsConnected) { try { byte[] bHead = new byte[8]; if (pipe.Read(bHead, 0, 8) == 8) { CMD_STREAM stCmd = new CMD_STREAM(); stCmd.uiParam = BitConverter.ToUInt32(bHead, 0); stCmd.uiSize = BitConverter.ToUInt32(bHead, 4); stCmd.bData = stCmd.uiSize == 0 ? null : new byte[stCmd.uiSize]; if (stCmd.uiSize == 0 || pipe.Read(stCmd.bData, 0, stCmd.bData.Length) == stCmd.bData.Length) { CMD_STREAM stRes = new CMD_STREAM(); pfnCmdProc.Invoke(stCmd, stRes); if (stRes.uiParam == (uint)ErrCode.CMD_NEXT) { // Emun用の繰り返しは対応しない throw new InvalidOperationException(); } else if (stRes.uiParam != (uint)ErrCode.CMD_NO_RES) { BitConverter.GetBytes(stRes.uiParam).CopyTo(bHead, 0); BitConverter.GetBytes(stRes.uiSize).CopyTo(bHead, 4); pipe.Write(bHead, 0, 8); if (stRes.uiSize != 0 && stRes.bData != null && stRes.bData.Length >= stRes.uiSize) { pipe.Write(stRes.bData, 0, (int)stRes.uiSize); } } } } pipe.WaitForPipeDrain(); pipe.Disconnect(); } catch { // Read & Write 中に切断されると例外が起きるはずなので一応 catch しておく } } } } })); m_ServerThread.Start(); return true; }
private void StopDesktopApplication(NamedPipeServerStream pipeStream, Thread dtThread) { UTF8Encoding encoding = new UTF8Encoding(); string message1 = "TestSuite Run Completed"; Byte[] bytes; bytes = encoding.GetBytes(message1); pipeStream.Write(bytes, 0, bytes.Length); pipeStream.Dispose(); if (dtThread != null) { dtThread.Abort(); } }
/// <summary>サーバ起動 - listenerスレッド関数</summary> private void ListeningNamedPipe() { // 通信シーケンスは自分で設計する // (本サンプルはリクエスト・レスポンス型の通信シーケンス)。 // 名前付きパイプ(サーバ) NamedPipeServerStream np = null; MemoryStream ms = null; // スレッドID int managedThreadId = Thread.CurrentThread.ManagedThreadId; try { // 名前付きパイプ(サーバ)を生成 // ※ 双方向のメッセージ ストリーム(最大5個オープン可能) np = new NamedPipeServerStream( "mypipe", PipeDirection.InOut, 5); // Listening開始を表示 this.SetResult_Svr( string.Format("Listening開始! - ThreadId:{0}", managedThreadId)); np.WaitForConnection(); //(待機) // 接続を表示 this.SetResult_Svr( string.Format("接続 - ThreadId:{0}", managedThreadId)); // 終了させるまで延々と読み続ける。 bool disConnect = false; byte[] buff = new byte[256]; byte[] byt = null; int bytSize = 0; string msg = ""; do { ms = new MemoryStream(); // 受信処理 while (true) { // 送信元(=クライアント)毎に読み込むことができる。 bytSize = np.Read(buff, 0, buff.Length); // 受信したメッセージをメモリに蓄積 ms.Write(buff, 0, bytSize); // 受信したメッセージを文字列に変換 msg = Encoding.UTF8.GetString(ms.ToArray()); // ここでは、シーケンス制御文字の // <end-send>が送られるまで受信を続行する。 if (msg.IndexOf("<end-send>") != -1) { // シーケンス制御文字を消去 msg = msg.Replace("<end-send>", ""); break; } // ここでは、シーケンス制御文字の // <end-connect>が送られるまで受信を続行する。 if (msg.IndexOf("<end-connect>") != -1) { // これがきたときに切断 disConnect = true; // シーケンス制御文字を消去 msg = msg.Replace("<end-connect>", ""); break; } } // 受信メッセージを表示 this.SetResult_Svr( string.Format("({0})受信:{1}", managedThreadId, msg)); // 反転処理 msg = CmnClass.strrev(msg); // 送信処理 if (!disConnect) // <end-connect>の際は、接続がクライアントから切断されている。 { // 送信処理 byt = Encoding.UTF8.GetBytes(msg + "<end-send>"); np.Write(byt, 0, byt.Length); // 送信メッセージを表示 this.SetResult_Svr( string.Format("({0})送信:{1}", managedThreadId, msg)); } } while (!disConnect); } catch (Exception ex) { // エラーを表示 this.SetResult_Svr( string.Format("({0})エラー:{1}", managedThreadId, ex.ToString())); } finally { if (np != null) { // 名前付きパイプ(サーバ)をクローズ np.Close(); } } // 切断を表示 this.SetResult_Svr( string.Format("切断 - ThreadId:{0}", managedThreadId)); }
private void WriteNumberToPipe(NamedPipeServerStream pipe, uint value) { byte[] buffer = BitConverter.GetBytes(value); pipe.Write(buffer, 0, buffer.Length); }
/// <summary> /// Send request with image and parametars. /// And recive processed image /// </summary> /// <param name="request"><see cref="https://github.com/Nedja995/npcv2/docs/named-pipe.md"/></param> /// <returns></returns> public byte[] Process(byte[] request) { IList<byte[]> image = new List<byte[]>(); _pipeServer = null; try { // Prepare the security attributes (the pipeSecurity parameter in // the constructor of NamedPipeServerStream) for the pipe. This // is optional. If pipeSecurity of NamedPipeServerStream is null, // the named pipe gets a default security descriptor.and the // handle cannot be inherited. The ACLs in the default security // descriptor of a pipe grant full control to the LocalSystem // account, (elevated) administrators, and the creator owner. // They also give only read access to members of the Everyone // group and the anonymous account. However, if you want to // customize the security permission of the pipe, (e.g. to allow // Authenticated Users to read from and write to the pipe), you // need to create a PipeSecurity object. PipeSecurity pipeSecurity = null; pipeSecurity = CreateSystemIOPipeSecurity(); // Create the named pipe. _pipeServer = new NamedPipeServerStream( PipeName, // The unique pipe name. PipeDirection.InOut, // The pipe is duplex NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // Message-based communication PipeOptions.None, // No additional parameters _bufferSize, // Input buffer size _bufferSize, // Output buffer size pipeSecurity, // Pipe security attributes HandleInheritability.None // Not inheritable ); Console.WriteLine("The named pipe ({0}) is created.", FullPipeName); // Wait for the client to connect. Console.WriteLine("Waiting for the client's connection..."); _pipeServer.WaitForConnection(); Console.WriteLine("Client is connected."); // string message; // // Send a response from server to client. // message = "Matrix4x4";//ResponseMessage; byte[] bResponse = Encoding.Unicode.GetBytes(message); int cbResponse = bResponse.Length; _pipeServer.Write(request, 0, request.Length); Console.WriteLine("Send {0} bytes to client: \"{1}\"", cbResponse, message.TrimEnd('\0')); // // Receive a request from client. // // Note: The named pipe was created to support message-based // communication. This allows a reading process to read // varying-length messages precisely as sent by the writing // process. In this mode you should not use StreamWriter to write // the pipe, or use StreamReader to read the pipe. You can read // more about the difference from the article: // http://go.microsoft.com/?linkid=9721786. // do { byte[] bRequest = new byte[_bufferSize]; int cbRequest = bRequest.Length, cbRead; cbRead = _pipeServer.Read(bRequest, 0, cbRequest); // SAVE TO ARRAY image.Add(bRequest); // Unicode-encode the received byte array and trim all the // '\0' characters at the end. message = Encoding.Unicode.GetString(bRequest).TrimEnd('\0'); // Console.WriteLine("Receive {0} bytes from client: \"{1}\"", // cbRead, message); } while (!_pipeServer.IsMessageComplete); // Flush the pipe to allow the client to read the pipe's contents // before disconnecting. Then disconnect the client's connection. _pipeServer.WaitForPipeDrain(); _pipeServer.Disconnect(); } catch (Exception ex) { Console.WriteLine("The server throws the error: {0}", ex.Message); } finally { if (_pipeServer != null) { _pipeServer.Close(); _pipeServer = null; } } byte[] ret = new byte[image.Count * 1024]; for (int i = 0; i < image.Count; i++) { for (int j = 0; j < 1024; j++) { ret[i * 1024 + j] = image[i][j]; } } return ret; }
public void ServiceRequest(NamedPipeServerStream nss) { var msgbuf = new List<byte>(8192); var rxbuf = new byte[256 * 1024]; int count = 0; Logging.Emit("reading from client"); do { count = nss.Read(rxbuf, msgbuf.Count, rxbuf.Length); if (count > 0) { msgbuf.AddRange(rxbuf.Take(count)); } } while (!nss.IsMessageComplete); Logging.Emit("server read {0} bytes", msgbuf.Count); // deserialize message from msgbuf var req = CClashMessage.Deserialize<CClashRequest>(msgbuf.ToArray()); cache.Setup(); // needed? Logging.Emit("processing request"); var resp = ProcessRequest(req); Logging.Emit("request complete: supported={0}, exitcode={1}", resp.supported, resp.exitcode); var tx = resp.Serialize(); nss.Write(tx, 0, tx.Length); nss.Flush(); Logging.Emit("server written {0} bytes", tx.Length); nss.WaitForPipeDrain(); nss.Disconnect(); Logging.Emit("request done"); }
public void writeMessage(NamedPipeServerStream stream, string message, bool addDefaultMessageType = false) { byte[] msg; if (addDefaultMessageType) msg = Encoding.ASCII.GetBytes("<" + m_defaultMessageType + ">" + message + "</" + m_defaultMessageType + ">"); else msg = Encoding.ASCII.GetBytes(message); stream.Write(msg, 0, msg.Length); }
// Record button private void btnRecord_Click(object sender, EventArgs e) { if (saveFileDialog1.FileName != null) { DateTime dt = DateTime.Now; saveFileName = String.Concat(Path.GetDirectoryName(saveFileDialog1.FileName), Path.DirectorySeparatorChar, Path.GetFileNameWithoutExtension(saveFileDialog1.FileName), dt.ToString("_yyMMdd_HHmmss"), ".int"); fs = new FileStream(saveFileName, FileMode.Create); binWriter = new BinaryWriter(fs); fileSize = 0.0; fileSaveTime = 0.0; saveMode = true; xSlowPos = 0; myUSBSource.Start(); btnZCheck.ForeColor = SystemColors.ControlDark; if (serialPort1.IsOpen) { String ArdComm = comboBox1.SelectedItem.ToString(); serialPort1.WriteLine(ArdComm); label7.Text="Arduino enabled"; } readMode = true; chkChannel1.Enabled = false; chkChannel2.Enabled = false; chkChannel3.Enabled = false; chkChannel4.Enabled = false; chkChannel5.Enabled = false; chkChannel6.Enabled = false; chkChannel7.Enabled = false; chkChannel8.Enabled = false; chkChannel9.Enabled = false; chkChannel10.Enabled = false; chkChannel11.Enabled = false; chkChannel12.Enabled = false; chkChannel13.Enabled = false; chkChannel14.Enabled = false; chkChannel15.Enabled = false; chkChannel16.Enabled = false; binWriter.Write((byte)128); binWriter.Write((byte)1); binWriter.Write((byte)1); displayChannel[0] = chkChannel1.Checked; displayChannel[1] = chkChannel2.Checked; displayChannel[2] = chkChannel3.Checked; displayChannel[3] = chkChannel4.Checked; displayChannel[4] = chkChannel5.Checked; displayChannel[5] = chkChannel6.Checked; displayChannel[6] = chkChannel7.Checked; displayChannel[7] = chkChannel8.Checked; displayChannel[8] = chkChannel9.Checked; displayChannel[9] = chkChannel10.Checked; displayChannel[10] = chkChannel11.Checked; displayChannel[11] = chkChannel12.Checked; displayChannel[12] = chkChannel13.Checked; displayChannel[13] = chkChannel14.Checked; displayChannel[14] = chkChannel15.Checked; displayChannel[15] = chkChannel16.Checked; if (checkBox1.Checked) { Console.WriteLine("Waiting for connection on named pipe mypipe"); System.IO.Pipes.NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream("mypipe"); namedPipeServerStream.WaitForConnection(); string line = "f**k"; byte[] buffer = ASCIIEncoding.ASCII.GetBytes(line); namedPipeServerStream.Write(buffer, 0, buffer.Length); namedPipeServerStream.Close(); } for (int channel = 0; channel < 16; channel++) { if (displayChannel[channel] == true) binWriter.Write((byte)1); else binWriter.Write((byte)0); } for (int i = 0; i < 48; i++) binWriter.Write((byte)0); } }
public static void ServerPInvokeChecks() { // calling every API related to server and client to detect any bad PInvokes using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { Task clientTask = StartClientAsync(PipeDirection.In); server.WaitForConnection(); Console.WriteLine("server.CanRead = {0}", server.CanRead); Console.WriteLine("server.CanSeek = {0}", server.CanSeek); Console.WriteLine("server.CanTimeout = {0}", server.CanTimeout); Console.WriteLine("server.CanWrite = {0}", server.CanWrite); Console.WriteLine("server.IsAsync = {0}", server.IsAsync); Console.WriteLine("server.IsConnected = {0}", server.IsConnected); Console.WriteLine("server.OutBufferSize = {0}", server.OutBufferSize); Console.WriteLine("server.ReadMode = {0}", server.ReadMode); Console.WriteLine("server.SafePipeHandle = {0}", server.SafePipeHandle); Console.WriteLine("server.TransmissionMode = {0}", server.TransmissionMode); server.Write(new byte[] { 123 }, 0, 1); server.WriteAsync(new byte[] { 124 }, 0, 1).Wait(); server.Flush(); server.WaitForPipeDrain(); clientTask.Wait(); } using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In)) { Task clientTask = StartClientAsync(PipeDirection.Out); server.WaitForConnection(); Console.WriteLine("server.InBufferSize = {0}", server.InBufferSize); byte[] readData = new byte[] { 0, 1 }; server.Read(readData, 0, 1); server.ReadAsync(readData, 1, 1).Wait(); Assert.Equal(123, readData[0]); Assert.Equal(124, readData[1]); } }