本文整理汇总了C#中System.IO.Pipes.NamedPipeServerStream.Write方法的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeServerStream.Write方法的具体用法?C# NamedPipeServerStream.Write怎么用?C# NamedPipeServerStream.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Pipes.NamedPipeServerStream
的用法示例。
在下文中一共展示了NamedPipeServerStream.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ServerSendsByteClientReceives
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]);
}
}
示例2: startServer
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
{
}
}
示例3: StartInternal
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();
}
}
}
示例4: Main
static void Main(string[] args)
{
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);
}
}
}
示例5: Main
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);
}
}
}
示例6: Test2
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);
}
示例7: ServerPInvokeChecks
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]);
}
}
示例8: NamedPipeFromStreamAsync
/// <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;
}
示例9: Run
/// <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);
//.........这里部分代码省略.........
示例10: tmrDraw_Tick
//.........这里部分代码省略.........
// 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]);
示例11: FakeSerialPort
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);
}
示例12: Main
//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));
//.........这里部分代码省略.........
示例13: BCLSystemIOPipeServer
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
//.........这里部分代码省略.........
示例14: SendUnityPipe
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());
//}
}
示例15: WriteSecretToPipe
private void WriteSecretToPipe(NamedPipeServerStream pipe, string secret)
{
byte[] buffer = Encoding.Unicode.GetBytes(secret);
WriteNumberToPipe(pipe, (uint)buffer.Length);
pipe.Write(buffer, 0, buffer.Length);
}