本文整理汇总了C#中System.IO.Pipes.NamedPipeClientStream.Read方法的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeClientStream.Read方法的具体用法?C# NamedPipeClientStream.Read怎么用?C# NamedPipeClientStream.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Pipes.NamedPipeClientStream
的用法示例。
在下文中一共展示了NamedPipeClientStream.Read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InvokeFunc
/// <summary>
/// Calls method with one parameter and result. Deserializes parameter and serialize result.
/// </summary>
/// <param name="type">Type containing method</param>
/// <param name="methodName">Name of method to call</param>
/// <param name="pipeName">Name of pipe to pass parameter and result</param>
static void InvokeFunc(Type type, string methodName, string pipeName)
{
using (var pipe = new NamedPipeClientStream(pipeName))
{
pipe.Connect();
var formatter = new BinaryFormatter();
ProcessThreadParams pars;
var lengthBytes = new byte[4];
pipe.Read(lengthBytes, 0, 4);
var length = BitConverter.ToInt32(lengthBytes, 0);
var inmemory = new MemoryStream(length);
var buf = new byte[1024];
while (length != 0)
{
var red = pipe.Read(buf, 0, buf.Length);
inmemory.Write(buf, 0, red);
length -= red;
}
inmemory.Position = 0;
try
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
return type.Assembly;
};
pars = (ProcessThreadParams)formatter.Deserialize(inmemory);
var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, pars.Types, null);
if (method == null) throw new InvalidOperationException("Method is not found: " + methodName);
if (pars.Pipe != null)
{
var auxPipe = new NamedPipeClientStream(pars.Pipe);
auxPipe.Connect();
for (int i = 0; i < pars.Parameters.Length; i++)
if (pars.Parameters[i] is PipeParameter) pars.Parameters[i] = auxPipe;
}
object result = method.Invoke(pars.Target, pars.Parameters);
var outmemory = new MemoryStream();
formatter.Serialize(outmemory, ProcessThreadResult.Successeded(result));
outmemory.WriteTo(pipe);
}
catch (TargetInvocationException e)
{
formatter.Serialize(pipe, ProcessThreadResult.Exception(e.InnerException));
throw e.InnerException;
}
catch (Exception e)
{
formatter.Serialize(pipe, ProcessThreadResult.Exception(e));
throw;
}
}
}
示例2: Main
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();
}
示例3: Main
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());
}
}
示例4: 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]);
}
}
示例5: Run
public void Run()
{
while (true)
{
using (pipeClient = new NamedPipeClientStream(
"localhost",
Config.PipeName,
PipeDirection.InOut,
PipeOptions.None
))
{
try
{
Console.Write("Waiting for new connection...");
pipeClient.Connect(5000);
Console.WriteLine("...Connected!");
pipeClient.ReadMode = PipeTransmissionMode.Message;
}
catch (Exception ex)
{
Console.WriteLine("...timed out :(");
}
try
{
while (pipeClient.IsConnected)
{
byte[] bResponse = new byte[Config.BufferSize];
int cbResponse = bResponse.Length;
int cbRead = pipeClient.Read(bResponse, 0, cbResponse);
var message = Encoding.Unicode.GetString(bResponse).TrimEnd('\0');
Console.WriteLine(message);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("Connection lost");
if (pipeClient != null)
{
Console.WriteLine("Cleaning up pipe connection...");
pipeClient.Close();
pipeClient = null;
}
}
}
}
}
示例6: Main
static void Main(string[] args)
{
string[] simpleNames = { "Yukari", "Maki", "Zunko", "Akane", "Aoi", "Koh" };
string[] simpleNamesA = { "yukari", "maki", "zunko", "akane", "aoi", "koh" };
//引数のチェック
if (args.Length < 2) {
string mergeName = "";
for (int i = 0; i < simpleNames.Length; i++)
{
mergeName = mergeName + simpleNames[i];
//ワード間に", "をつける
if (i < simpleNames.Length - 1)
mergeName = mergeName + ", ";
}
Console.WriteLine("引数を指定してください: VoiceroidTClient"+ mergeName +" [会話内容];[音量0.0-2.0];[話速0.5-4.0];[高さ0.5-2.0];[抑揚0.0-2.0]");
return;
}
//引数に設定されたボイスロイドの名前をチェック
string selectedSimple = null;
for (int i = 0; i < simpleNames.Length; i++) {
if (args[0].CompareTo(simpleNames[i]) == 0 || args[0].CompareTo(simpleNamesA[i]) == 0) {
selectedSimple = simpleNames[i];
}
}
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;
}
//サーバーとの通信処理を開始
string message = args[1];
try {
//サーバーのセッションを取得する
using (NamedPipeClientStream client = new NamedPipeClientStream("voiceroid_talker" + selectedSimple)) {
client.Connect(1000);
//サーバにーメッセージを送信する
byte[] buffer = UnicodeEncoding.Unicode.GetBytes(message);
client.Write(buffer, 0, buffer.Length);
byte[] response = new byte[4];
client.Read(response, 0, response.Length);
client.Close();
}
} catch (Exception e) {
//サーバーに接続できない時、通信エラーが発生した場合
Console.WriteLine("VoiceroidTServerによるサーバー, [voiceroid_talker" + selectedSimple + "]が見つかりません.");
}
}
示例7: SendCommand
private void SendCommand(int pid, string command)
{
var clientStream = new NamedPipeClientStream(".", this.PipeNameForPid(pid), PipeDirection.InOut, PipeOptions.Asynchronous);
clientStream.Connect(500);
clientStream.ReadMode = PipeTransmissionMode.Message;
var commandBytes = Encoding.ASCII.GetBytes(command);
byte[] buffer = new byte[256];
var responseBuilder = new StringBuilder();
clientStream.Write(commandBytes, 0, commandBytes.Length);
int read = clientStream.Read(buffer, 0, buffer.Length);
responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));
while (!clientStream.IsMessageComplete)
{
read = clientStream.Read(buffer, 0, buffer.Length);
responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));
}
this.ProcessResponse(responseBuilder.ToString());
}
示例8: ReadCommandFromEnviroGen
private static byte[] ReadCommandFromEnviroGen(NamedPipeClientStream pipe)
{
//We read into this buffer because this will block until we get a byte,
//which is what we want in this case.
var commandRead = new byte[1];
pipe.Read(commandRead, 0, 1);
Console.WriteLine($"Raw command read: {commandRead[0]}");
var commandLength = ServerCommands.CommandLengths[commandRead[0]];
var input = new byte[1 + commandLength];
input[0] = commandRead[0];
if (commandLength > 0)
{
//TODO: handle improper number of bytes sent, currently this just blocks if the amount is too low
//Read all the command args into the input array
pipe.Read(input, 1, commandLength);
}
return input;
}
示例9: Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
_spyMgr.LoadCustomDll(_process, @"..\..\..\Plugin\bin\Plugins\CRegistryPlugin.dll", false, false);
pipe = new NamedPipeClientStream(".", "HyperPipe32", PipeDirection.InOut);
pipe.Connect();
byte[] data = new byte[4];
pipe.Read(data, 0, 4);
Int32 address = BitConverter.ToInt32(data, 0);
NktHook hook = _spyMgr.CreateHookForAddress((IntPtr)address, "D3D9.DLL!CreateDevice", (int)(eNktHookFlags.flgRestrictAutoHookToSameExecutable | eNktHookFlags.flgOnlyPostCall | eNktHookFlags.flgDontCheckAddress));
hook.AddCustomHandler(@"..\..\..\Plugin\bin\Plugins\CRegistryPlugin.dll", 0, "");
hook.Attach(_process, true);
hook.Hook(true);
_spyMgr.ResumeProcess(_process, continueevent);
}
示例10: ChunkRequestSpeedTest
private static void ChunkRequestSpeedTest(object data)
{
//initialize world
SendCommandToEnviroGen(new byte[] { 1, 10, 10});
var getChunkCommand = new byte[] { 4, 0, 0 };
m_Watch.Start();
for (var i = 0; i < 1000; i++)
{
var pipe = new NamedPipeClientStream(".", m_OutputPipeName, PipeDirection.InOut);
pipe.Connect();
pipe.Write(getChunkCommand, 0, getChunkCommand.Length);
var input = new byte[32768 + 1];
pipe.Read(input, 0, input.Length);
}
m_Watch.Stop();
Console.WriteLine($"EnviroGen took {m_Watch.ElapsedMilliseconds}ms to serve 1000 chunks.");
Console.WriteLine($"Average Time: {m_Watch.ElapsedMilliseconds / 1000f}ms");
m_Watch.Reset();
Console.ReadLine();
}
示例11: SendD3Cmd
private D3Header SendD3Cmd()
{
Thread.Sleep(10); // damit CPU nicht ausgelastet wird. so CPU is not busy.
lock (this)
{
object bufferOBJ = (object)this.D3Mail;
if (this.D3Process != null)
{
byte[] ByteStruct = new byte[Marshal.SizeOf(this.D3Mail)];
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(this.D3Mail));
Marshal.StructureToPtr(this.D3Mail, ptr, true);
Marshal.Copy(ptr, ByteStruct, 0, Marshal.SizeOf(this.D3Mail));
Marshal.FreeHGlobal(ptr);
NamedPipeClientStream pipeClient;
pipeClient = new NamedPipeClientStream(".", "D3_" + this.D3Process.Id, PipeDirection.InOut);
try
{
pipeClient.Connect(200);
if (pipeClient.IsConnected)
{
pipeClient.Write(ByteStruct, 0, Marshal.SizeOf(this.D3Mail));
pipeClient.Read(ByteStruct, 0, Marshal.SizeOf(this.D3Mail));
}
IntPtr i = Marshal.AllocHGlobal(Marshal.SizeOf(bufferOBJ));
Marshal.Copy(ByteStruct, 0, i, Marshal.SizeOf(bufferOBJ));
bufferOBJ = Marshal.PtrToStructure(i, bufferOBJ.GetType());
Marshal.FreeHGlobal(i);
}
catch (Exception e) { _logger.Log("[IPlugin] D3 Command Exception." + e); }
finally
{
pipeClient.Close();
}
}
return this.D3Mail = (D3Header)bufferOBJ;
}
}
示例12: QvxCommandWorker
private void QvxCommandWorker()
{
try
{
if (pipeName == null) return;
object state = new object();
object connection = null;
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
{
var buf = new byte[4];
var buf2 = new byte[4];
Int32 count = 0;
Int32 datalength = 0;
pipeClient.Connect(1000);
while (pipeClient.IsConnected)
{
try
{
#region Get QvxRequest
var iar = pipeClient.BeginRead(buf, 0, 4, null, state);
while (!iar.IsCompleted) Thread.Sleep(1);
count = pipeClient.EndRead(iar);
if (count != 4) throw new Exception("Invalid Count Length");
buf2[0] = buf[3];
buf2[1] = buf[2];
buf2[2] = buf[1];
buf2[3] = buf[0];
datalength = BitConverter.ToInt32(buf2, 0);
var data = new byte[datalength];
count = pipeClient.Read(data, 0, datalength);
if (count != datalength) throw new Exception("Invalid Data Length");
var sdata = ASCIIEncoding.ASCII.GetString(data);
sdata = sdata.Replace("\0", "");
QvxRequest request;
try
{
request = QvxRequest.Deserialize(sdata);
}
catch (Exception ex)
{
logger.Error(ex);
throw ex;
}
request.QVWindow = QVWindow;
request.Connection = connection;
#endregion
#region Handle QvxRequets
QvxReply result = null;
if (HandleQvxRequest != null)
result = HandleQvxRequest(request);
if (result == null)
result = new QvxReply() { Result = QvxResult.QVX_UNKNOWN_ERROR };
#endregion
#region Send QvxReply
sdata = " " + result.Serialize() + "\0";
datalength = sdata.Length - 4;
buf2 = ASCIIEncoding.ASCII.GetBytes(sdata);
buf = BitConverter.GetBytes(datalength);
buf2[0] = buf[3];
buf2[1] = buf[2];
buf2[2] = buf[1];
buf2[3] = buf[0];
pipeClient.Write(buf2, 0, buf2.Length);
pipeClient.WaitForPipeDrain();
#endregion
#region Handle result States
if (result.Terminate)
close = true;
if (result.Connection != null)
connection = result.Connection;
if (result.SetConnectionNULL)
connection = null;
#endregion
}
catch (Exception ex)
{
logger.Error(ex);
Thread.Sleep(500);
close = true;
}
if (close)
{
close = false;
pipeClient.Close();
}
Thread.Sleep(5);
}
}
running = false;
}
//.........这里部分代码省略.........
示例13: ClientPInvokeChecks
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;
}
}
}
示例14: SendD3Cmd
private D3Header SendD3Cmd(D3Header SendBuffer)
{
Thread.Sleep(5); // damit CPU nicht ausgelastet wird.
lock (this)
{
object bufferOBJ = (object)SendBuffer;
byte[] ByteStruct = new byte[Marshal.SizeOf(SendBuffer)];
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(SendBuffer));
Marshal.StructureToPtr(SendBuffer, ptr, true);
Marshal.Copy(ptr, ByteStruct, 0, Marshal.SizeOf(SendBuffer));
Marshal.FreeHGlobal(ptr);
NamedPipeClientStream pipeClient;
SendBuffer.returnValue1.i = -1;
SendBuffer.returnValue2.i = -1;
SendBuffer.returnValue1.f = -1;
SendBuffer.returnValue2.f = -1;
try
{
pipeClient = new NamedPipeClientStream(".", "D3_" + this.D3Process.Id, PipeDirection.InOut);
pipeClient.Connect(1000);
if (pipeClient.IsConnected)
{
pipeClient.Write(ByteStruct, 0, Marshal.SizeOf(SendBuffer));
pipeClient.Read(ByteStruct, 0, Marshal.SizeOf(SendBuffer));
}
IntPtr i = Marshal.AllocHGlobal(Marshal.SizeOf(bufferOBJ));
Marshal.Copy(ByteStruct, 0, i, Marshal.SizeOf(bufferOBJ));
bufferOBJ = Marshal.PtrToStructure(i, bufferOBJ.GetType());
Marshal.FreeHGlobal(i);
pipeClient.Close();
}
catch { }
return (D3Header)bufferOBJ;
}
}
示例15: ClientPInvokeChecks
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();
}
}
}