本文整理汇总了C#中System.IO.Pipes.NamedPipeServerStream.WaitForPipeDrain方法的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeServerStream.WaitForPipeDrain方法的具体用法?C# NamedPipeServerStream.WaitForPipeDrain怎么用?C# NamedPipeServerStream.WaitForPipeDrain使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Pipes.NamedPipeServerStream
的用法示例。
在下文中一共展示了NamedPipeServerStream.WaitForPipeDrain方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
}
}
示例2: Listen
//server
private void Listen(NamedPipeServerStream server, StreamWriter writer)
{
var buffer = new byte[4096];
#region
//server.BeginRead(buffer, 0, 4096, p =>
//{
// Trace.WriteLine(p.IsCompleted);
// server.EndRead(p);
// var reader = new StreamReader(server);
// var temp = string.Empty;
// while (!string.IsNullOrEmpty((temp = reader.ReadLine())))
// {
// Trace.WriteLine("Server:from client " + temp);
// writer.WriteLine("echo:" + temp);
// writer.Flush();
// break;
// }
// server.Disconnect();
// Listen(server, writer);
//}, null);
#endregion
server.BeginWaitForConnection(new AsyncCallback(o =>
{
var pipe = o.AsyncState as NamedPipeServerStream;
pipe.EndWaitForConnection(o);
var reader = new StreamReader(pipe);
var result = reader.ReadLine();
var text = string.Format("connected:receive from client {0}|{1}", result.Length, result);
Trace.WriteLine(text);
writer.WriteLine(result);
writer.Flush();
writer.WriteLine("End");
writer.Flush();
server.WaitForPipeDrain();
server.Disconnect();
Listen(pipe, writer);
}), server);
}
示例3: 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);
}
示例4: DoListen
void DoListen()
{
while (true)
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream (pipePath, PipeDirection.InOut, numPipeThreads, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, (int)Protocol.MaxMessageLength, (int)Protocol.MaxMessageLength)) {
Console.WriteLine ("Waiting for client on path " + pipePath);
pipeServer.WaitForConnection ();
Console.WriteLine ("Client connected");
ServerConnection conn;
if (!AcceptClient (pipeServer, out conn)) {
Console.WriteLine ("Client rejected");
pipeServer.Disconnect ();
continue;
}
pipeServer.Flush ();
pipeServer.WaitForPipeDrain ();
if (NewConnection != null)
NewConnection (conn);
while (conn.IsConnected)
conn.Iterate ();
pipeServer.Disconnect ();
}
}
示例5: ServerPInvokeChecks
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]);
}
}
示例6: ServiceRequest
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");
}
示例7: OutOfProcessBuild
private static BuildResult OutOfProcessBuild (Dictionary<string, object> arguments, int startupTimeoutMs = 5000) {
var jss = new JavaScriptSerializer {
MaxJsonLength = 1024 * 1024 * 64
};
var argsJson = jss.Serialize(arguments);
var pipeId = String.Format("JSIL.Build{0:X4}", (new Random()).Next());
Console.Error.WriteLine("// Starting out-of-process solution build with ID '{0}'...", pipeId);
using (var pipe = new NamedPipeServerStream(
pipeId, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous
)) {
var psi = new ProcessStartInfo {
FileName = Process.GetCurrentProcess().MainModule.FileName,
Arguments = String.Format("--buildSolution {0}", pipeId),
WorkingDirectory = Environment.CurrentDirectory,
CreateNoWindow = false,
UseShellExecute = false,
ErrorDialog = false
};
var childProcess = Process.Start(psi);
if (childProcess == null)
throw new InvalidOperationException("Failed to start child process");
var connectedEvent = new ManualResetEventSlim(false);
var exitedEvent = new ManualResetEventSlim(false);
try {
var connectAR = pipe.BeginWaitForConnection((_) => connectedEvent.Set(), null);
try {
childProcess.Exited += (s, e) => exitedEvent.Set();
if (childProcess.HasExited)
exitedEvent.Set();
} catch {
}
WaitHandle.WaitAny(
new[] { connectedEvent.WaitHandle, exitedEvent.WaitHandle }, startupTimeoutMs
);
if (connectedEvent.IsSet) {
pipe.EndWaitForConnection(connectAR);
} else if (exitedEvent.IsSet) {
Console.Error.WriteLine("// Out-of-process solution build terminated unexpectedly with code {0}!", childProcess.ExitCode);
Environment.Exit(1);
} else {
Console.Error.WriteLine("// Out-of-process solution build timed out!");
Environment.Exit(2);
}
using (var sr = new StreamReader(pipe))
using (var sw = new StreamWriter(pipe)) {
sw.WriteLine(argsJson);
sw.Flush();
pipe.Flush();
pipe.WaitForPipeDrain();
var resultJson = sr.ReadLine();
var buildResult = jss.Deserialize<BuildResult>(resultJson);
Console.Error.WriteLine("// Out-of-process solution build completed successfully.");
return buildResult;
}
} finally {
try {
if (!childProcess.HasExited)
childProcess.Kill();
} catch {
}
childProcess.Dispose();
}
}
}
示例8: Run
//.........这里部分代码省略.........
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;
}
}
}
示例9: 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]);
}
}
示例10: Process
/// <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);
//.........这里部分代码省略.........
示例11: PrivateRunAsync
private async Task PrivateRunAsync(CancellationToken cancellationToken)
{
using (var pipe = new NamedPipeServerStream(ServerInfo.Name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
while (!cancellationToken.IsCancellationRequested)
{
await pipe.WaitForConnectionAsync(cancellationToken);
using (var reader = new NonClosingStreamReader(pipe))
using (var writer = new NonClosingStreamWriter(pipe) { AutoFlush = true })
{
var input = await reader.ReadCommandAsync();
_log.Information("Retrieved input {Input}", input);
switch (input)
{
case NamedPipeCommand.FindRepo:
await writer.WriteAsync(NamedPipeCommand.Ready);
await FindRepo(writer, await reader.ReadLineAsync(), cancellationToken);
break;
case NamedPipeCommand.GetAllRepos:
await writer.WriteAsync(NamedPipeCommand.Ready);
await GetAllRepos(writer, cancellationToken);
break;
case NamedPipeCommand.RemoveRepo:
await writer.WriteAsync(NamedPipeCommand.Ready);
await RemoveRepo(writer, reader, cancellationToken);
break;
case NamedPipeCommand.ClearCache:
await writer.WriteAsync(NamedPipeCommand.Ready);
await ProcessClearCacheAsync(writer, cancellationToken);
break;
case NamedPipeCommand.ExpandGitCommand:
await writer.WriteAsync(NamedPipeCommand.Ready);
await ProcessExpandGitCommandAsync(writer, reader, cancellationToken);
break;
default:
await writer.WriteAsync(NamedPipeCommand.BadCommand);
break;
}
}
// This must be after the reader and writer are closed
// Otherwise, an InvalidOperationException is thrown
pipe.WaitForPipeDrain();
pipe.Disconnect();
}
}
}
示例12: RunCopierExecutable
private RunStatus RunCopierExecutable(string fullExePath, StringLineReceived stdoutLineReceived,
IEnumerable<string> executableInput = null, bool runAsAdmin = false)
{
var outStatus = new RunStatus();
using (var proc = new Process())
{
string clientGuidStr = Guid.NewGuid().ToString();
;
var stdPipeSvr = new NamedPipeServerStream("Copier_" + clientGuidStr + "_data",
PipeDirection.InOut, 1, PipeTransmissionMode.Byte);
var errPipeSvr = new NamedPipeServerStream("Copier_" + clientGuidStr + "_error",
PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
proc.StartInfo = new ProcessStartInfo(fullExePath, clientGuidStr);
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (runAsAdmin)
proc.StartInfo.Verb = "runas";
proc.Start();
var endEvent = new AutoResetEvent(false);
errPipeSvr.BeginWaitForConnection(iar =>
{
var pipSvr = (NamedPipeServerStream) iar.AsyncState;
try
{
pipSvr.EndWaitForConnection(iar);
var errSb = new StringBuilder();
var readBuffer = new byte[4096];
pipSvr.BeginRead(readBuffer, 0, readBuffer.Length, iar2 =>
{
var pipeStr = (NamedPipeServerStream) iar2.AsyncState;
int numBytes = pipeStr.EndRead(iar2);
if (numBytes > 0)
{
string recvStr = Encoding.UTF8.GetString(readBuffer, 0, numBytes);
errSb.Append(recvStr);
}
else //EOF
{
outStatus.ErrorString = errSb.ToString().TrimEnd('\r', '\n');
pipeStr.Close();
endEvent.Set();
}
}, pipSvr);
}
catch (ObjectDisposedException)
{
} //happens if no connection happened
}, errPipeSvr);
stdPipeSvr.WaitForConnection();
if (executableInput != null)
{
var sw = new StreamWriter(stdPipeSvr, Encoding.UTF8);
foreach (string line in executableInput)
sw.WriteLine(line);
//last one to indicate no more input
sw.WriteLine();
sw.Flush();
}
stdPipeSvr.WaitForPipeDrain(); //wait for process to read all bytes we sent it
using (var sr = new StreamReader(stdPipeSvr, Encoding.UTF8, false))
{
while (stdPipeSvr.IsConnected)
{
string recvLine = sr.ReadLine();
if (stdoutLineReceived != null)
stdoutLineReceived(stdPipeSvr, recvLine);
if (recvLine == null)
break; //EOF
}
sr.Close(); //closes the underlying named pipe as well
}
proc.WaitForExit();
outStatus.ExitCode = proc.ExitCode;
if (outStatus.ExitCode != 0)
endEvent.WaitOne(); //wait for stderr to be read
}
return outStatus;
}
示例13: Offer
public void Offer(Stream s)
{
if (thr != null)
throw new InvalidOperationException("Can only serve one thing at a time!");
if (e != null)
throw new InvalidOperationException("Previous attempt failed!", e);
if (!s.CanRead)
throw new ArgumentException("Stream must be readable!");
using (var evt = new ManualResetEventSlim())
{
thr = new Thread(delegate()
{
try
{
using (var srv = new NamedPipeServerStream(PipeName, PipeDirection.Out))
{
evt.Set();
srv.WaitForConnection();
s.CopyTo(srv);
srv.WaitForPipeDrain();
}
}
catch (Exception ee)
{
e = ee;
}
});
thr.Start();
evt.Wait();
}
}
示例14: Start
public void Start()
{
Console.WriteLine("Обед философов начался ! Всего {0} столовых приборов !", _forksCount);
bool hasStarted = false;
while (_connectedPhilosopherCount > 0 || !hasStarted)
{
_pipeServer = CreateServerPipe();
_pipeServer.WaitForConnection();
var request = (Request)_pipeServer.ReadByte();
switch(request)
{
case Request.GetPhilosopherPosition:
AssignPhilosopherPosition();
hasStarted = true;
break;
case Request.Eat:
Eat();
break;
case Request.Think:
Think();
break;
case Request.Rest:
Rest();
break;
case Request.TakeFork:
TakeFork();
break;
case Request.PutFork:
PutDownFork();
break;
default:
break;
}
_pipeServer.WaitForPipeDrain();
}
Console.WriteLine("Все ушли !");
Console.ReadLine();
}
示例15: StartServer
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;
}