本文整理汇总了C#中System.IO.Pipes.NamedPipeServerStream.Read方法的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeServerStream.Read方法的具体用法?C# NamedPipeServerStream.Read怎么用?C# NamedPipeServerStream.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Pipes.NamedPipeServerStream
的用法示例。
在下文中一共展示了NamedPipeServerStream.Read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PipesReader
private static void PipesReader(string pipeName)
{
try
{
using (var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In))
{
pipeReader.WaitForConnection();
WriteLine("reader connected");
const int BUFFERSIZE = 256;
bool completed = false;
while (!completed)
{
byte[] buffer = new byte[BUFFERSIZE];
int nRead = pipeReader.Read(buffer, 0, BUFFERSIZE);
string line = Encoding.UTF8.GetString(buffer, 0, nRead);
WriteLine(line);
if (line == "bye") completed = true;
}
}
WriteLine("completed reading");
ReadLine();
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
}
示例2: 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();
}
}
}
示例3: ClientSendsByteServerReceives
public static void ClientSendsByteServerReceives()
{
using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In))
{
byte[] sent = new byte[] { 123 };
byte[] received = new byte[] { 0 };
Task t = Task.Run(() =>
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out))
{
client.Connect();
Assert.True(client.IsConnected);
client.Write(sent, 0, 1);
}
});
server.WaitForConnection();
Assert.True(server.IsConnected);
int bytesReceived = server.Read(received, 0, 1);
Assert.Equal(1, bytesReceived);
t.Wait();
Assert.Equal(sent[0], received[0]);
}
}
示例4: PipeThreadStart
private void PipeThreadStart()
{
PipeSecurity pSec = new PipeSecurity();
PipeAccessRule pAccRule = new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)
, PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize, System.Security.AccessControl.AccessControlType.Allow);
pSec.AddAccessRule(pAccRule);
using (_pipeServer = new NamedPipeServerStream("NKT_SQLINTERCEPT_PIPE",
PipeDirection.InOut,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
PipeOptions.None,
MAX_STRING_CCH * 2,
MAX_STRING_CCH * 2,
pSec,
HandleInheritability.Inheritable))
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("(pipe thread) Waiting for connection...");
Console.ForegroundColor = ConsoleColor.Gray;
try
{
_pipeServer.WaitForConnection();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("(pipe thread) Client connected.");
Console.ForegroundColor = ConsoleColor.Gray;
while (true)
{
byte[] readBuf = new byte[MAX_STRING_CCH * 2];
int cbRead = _pipeServer.Read(readBuf, 0, MAX_STRING_CCH * 2);
string str = Encoding.Unicode.GetString(readBuf, 0, cbRead);
Console.WriteLine(str);
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("--------------------------------------------------------");
Console.ForegroundColor = ConsoleColor.Gray;
if (_blockQuery)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("(pipe thread) QUERY ABORTED");
Console.ForegroundColor = ConsoleColor.Gray;
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("(pipethread) Pipe or data marshaling operation exception! ({0})", ex.Message);
}
}
}
示例5: SetupPipeWait
static void SetupPipeWait(App app)
{
var pipe = new NamedPipeServerStream(IPCName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
pipe.BeginWaitForConnection(result =>
{
pipe.EndWaitForConnection(result);
var buf = new byte[sizeof(int)];
pipe.Read(buf, 0, buf.Length);
var len = BitConverter.ToInt32(buf, 0);
buf = new byte[len];
pipe.Read(buf, 0, buf.Length);
var commandLine = Coder.BytesToString(buf, Coder.CodePage.UTF8);
app.Dispatcher.Invoke(() => app.CreateWindowsFromArgs(commandLine));
SetupPipeWait(app);
}, null);
}
示例6: ProcessMessages
public bool ProcessMessages(NamedPipeServerStream server)
{
try
{
//BinaryReader would throw EndOfStreamException
byte[] buffer = new byte[4];
if (server.Read(buffer, 0, 4) == 0)
return false;
int count = BitConverter.ToInt32(buffer, 0);
var rawTouchDatas = new List<RawTouchData>(count);
for (int i = 0; i < count; i++)
{
buffer = new byte[13];
server.Read(buffer, 0, 1);
server.Read(buffer, 1, 4);
server.Read(buffer, 5, 4);
server.Read(buffer, 9, 4);
bool tip = BitConverter.ToBoolean(buffer, 0);
int contactIdentifier = BitConverter.ToInt32(buffer, 1);
int x = BitConverter.ToInt32(buffer, 5);
int y = BitConverter.ToInt32(buffer, 9);
rawTouchDatas.Add(new RawTouchData(tip, contactIdentifier, new Point(x, y)));
}
_synchronizationContext.Post(o =>
{
PointsIntercepted?.Invoke(this, new RawPointsDataMessageEventArgs(rawTouchDatas));
}, null);
}
catch (Exception exception)
{
Logging.LogException(exception);
return false;
}
return true;
}
示例7: ThreadStartServer
protected void ThreadStartServer() {
// Some idiot MS intern must have written the blocking part of pipes. There is no way to
// cancel WaitForConnection, or ReadByte. (pipes introduced in 3.5, I thought one time I read
// that 4.0 added an abort option, but I cannot find it)
// If you set Async as the option, but use sync calls, .Close can kind of kill them.
// It causes exceptions to be raised in WaitForConnection and ReadByte (possibly due to another
// issue with threads and exceptions without handlers, maybe check again later), but they just
// loop over and over on it... READ however with the async option WILL exit with 0....
// Its like VB1 and adding to sorted listboxes over all again... no one dogfooded this stuff.
// And yes we could use async.. but its SOOO much messier and far more complicated than it ever
// should be.
//
// Here is an interesting approach using async and polling... If need be we can go that way:
// http://stackoverflow.com/questions/2700472/how-to-terminate-a-managed-thread-blocked-in-unmanaged-code
while (!KillThread)
{
// Loop again to allow mult incoming connections between debug sessions
try
{
using (mPipe = new NamedPipeServerStream(mPipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) {
mPipe.WaitForConnection();
ushort xCmd;
int xSize;
while (mPipe.IsConnected && !KillThread) {
xCmd = (ushort)(ReadByte() << 8);
xCmd |= ReadByte();
xSize = ReadByte() << 24;
xSize = xSize | ReadByte() << 16;
xSize = xSize | ReadByte() << 8;
xSize = xSize | ReadByte();
byte[] xMsg = new byte[xSize];
mPipe.Read(xMsg, 0, xSize);
if (DataPacketReceived != null)
{
DataPacketReceived(xCmd, xMsg);
}
}
}
} catch (Exception) {
// Threads MUST have an exception handler
// Otherwise there are side effects when an exception occurs
}
}
}
示例8: createPipeServer
public static void createPipeServer()
{
Decoder decoder = Encoding.Default.GetDecoder();
Byte[] bytes = new Byte[BufferSize];
char[] chars = new char[BufferSize];
int numBytes = 0;
StringBuilder msg = new StringBuilder();
ownerInvoker = new Invoker(owner);
ownerInvoker.sDel = ExecuteCommand;
pipeName = "BarcodeServer";
try
{
pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1,
PipeTransmissionMode.Message,
PipeOptions.Asynchronous);
while (true)
{
pipeServer.WaitForConnection();
do
{
msg.Length = 0;
do
{
numBytes = pipeServer.Read(bytes, 0, BufferSize);
if (numBytes > 0)
{
int numChars = decoder.GetCharCount(bytes, 0, numBytes);
decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
msg.Append(chars, 0, numChars);
}
} while (numBytes > 0 && !pipeServer.IsMessageComplete);
decoder.Reset();
if (numBytes > 0)
{
ownerInvoker.Invoke(msg.ToString());
}
} while (numBytes != 0);
pipeServer.Disconnect();
}
}
catch (Exception)
{
//throw new Exception("Failed to create pipeServer! the detailed messages are: " + ex.Message);
//MessageBox.Show(ex.Message);
}
}
示例9: createPipeServer
public static void createPipeServer()
{
Decoder decoder = Encoding.Default.GetDecoder();
Byte[] bytes = new Byte[BufferSize];
char[] chars = new char[BufferSize];
int numBytes = 0;
StringBuilder msg = new StringBuilder();
try
{
pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
while (true)
{
pipeServer.WaitForConnection();
do
{
msg.Length = 0;
do
{
numBytes = pipeServer.Read(bytes, 0, BufferSize);
if (numBytes > 0)
{
int numChars = decoder.GetCharCount(bytes, 0, numBytes);
decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
msg.Append(chars, 0, numChars);
}
} while (numBytes > 0 && !pipeServer.IsMessageComplete);
decoder.Reset();
if (numBytes > 0)
{
//Notify the UI for message received
if (owner != null)
owner.Dispatcher.Invoke(DispatcherPriority.Send, new Action<string>(owner.OnMessageReceived), msg.ToString());
//ownerInvoker.Invoke(msg.ToString());
}
} while (numBytes != 0);
pipeServer.Disconnect();
}
}
catch (Exception)
{
throw;
}
}
示例10: Main
static void Main(string[] args)
{
Console.WriteLine("Creating pipe {0}", PIPE_NAME);
NamedPipeServerStream pipeServer = new NamedPipeServerStream(
PIPE_NAME,
PipeDirection.InOut,
10,
PipeTransmissionMode.Message,
PipeOptions.None
);
Console.WriteLine("Waiting for connection.");
pipeServer.WaitForConnection();
Console.WriteLine("Client connected.");
int bytes_read;
while(true)
{
Byte[] buffer = new Byte[4096];
StringBuilder sb = new StringBuilder();
do
{
bytes_read = pipeServer.Read(buffer, 0, buffer.Length);
sb.Append(Encoding.UTF8.GetChars(buffer, 0, bytes_read));
if (pipeServer.IsMessageComplete)
{
break;
}
}
while (!pipeServer.IsMessageComplete);
if (bytes_read == 0)
{
Console.WriteLine("Received empty message, quitting.");
break;
}
Console.WriteLine("Message received: {0}", sb.ToString());
}
Console.WriteLine("Done");
}
示例11: 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);
}
示例12: StartPipeServer
public void StartPipeServer()
{
serverStream = new NamedPipeServerStream("zjlrcpipe",
PipeDirection.InOut,
10,
PipeTransmissionMode.Message,
PipeOptions.None);
serverStream.ReadMode = PipeTransmissionMode.Message;
Byte[] bytes = new Byte[1024];
UTF8Encoding encoding = new UTF8Encoding();
int numBytes;
while (running)
{
serverStream.WaitForConnection();
string message = "";
do
{
numBytes = serverStream.Read(bytes, 0, bytes.Length);
message += encoding.GetString(bytes, 0, numBytes);
} while (!serverStream.IsMessageComplete);
string[] pas = message.Split('|');
if (null != pas && pas.Length >= 3)
{
if (!(pas[0] == "exit" && pas[1] == "exit" && pas[2] == "exit"))
main.Dispatcher.Invoke(main.searchLrcByZLP, pas[0], pas[1], pas[2]);
else
running = false;
}
serverStream.Disconnect();
}
serverStream.Dispose();
}
示例13: Init
private void Init()
{
if (PipeExists(PIPENAME)) {
using (NamedPipeClientStream client = new NamedPipeClientStream(PIPENAME)) {
try {
client.Connect(2000);
client.Write(SHOW, 0, SHOW.Length);
client.WaitForPipeDrain();
}
catch {
}
}
Environment.Exit(1);
}
using (NamedPipeServerStream server = new NamedPipeServerStream(PIPENAME)) {
while (true) {
server.WaitForConnection();
byte[] data = new byte[255];
int count = server.Read(data, 0, data.Length);
string msg = Encoding.ASCII.GetString(data, 0, count).ToUpper();
if (msg.Equals("SHOW")) {
main.Invoke(new MethodInvoker(delegate
{
main.Show();
main.WindowState = FormWindowState.Normal;
}));
}
else if (msg.Equals("BREAK")) {
break;
}
else if (msg.Equals("EXIT")) {
Environment.Exit(0);
}
server.Disconnect();
}
}
}
示例14: ServerCloneTests
public static async Task ServerCloneTests()
{
const string pipeName = "fooclone";
byte[] msg1 = new byte[] { 5, 7, 9, 10 };
byte[] received1 = new byte[] { 0, 0, 0, 0 };
using (NamedPipeServerStream serverBase = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte))
using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None))
{
Task clientTask = Task.Run(() =>
{
client.Connect();
client.Write(msg1, 0, msg1.Length);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(1, client.NumberOfServerInstances);
}
});
serverBase.WaitForConnection();
using (NamedPipeServerStream server = new NamedPipeServerStream(PipeDirection.In, false, true, serverBase.SafePipeHandle))
{
int len1 = server.Read(received1, 0, msg1.Length);
Assert.Equal(msg1.Length, len1);
Assert.Equal(msg1, received1);
await clientTask;
}
}
}
示例15: ReadThreadStart
private void ReadThreadStart(NamedPipeServerStream decodePipe, Process encoder)
{
const int bufSize = 1024 * 1024;
byte[] buffer = new byte[bufSize];
decodePipe.WaitForConnection();
while (decodePipe.IsConnected && !encoder.HasExited)
{
int readCnt = decodePipe.Read(buffer, 0, bufSize);
encoder.StandardInput.BaseStream.Write(buffer, 0, readCnt);
}
encoder.StandardInput.BaseStream.Close();
}