本文整理汇总了C#中System.IO.Pipes.NamedPipeClientStream.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeClientStream.Flush方法的具体用法?C# NamedPipeClientStream.Flush怎么用?C# NamedPipeClientStream.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Pipes.NamedPipeClientStream
的用法示例。
在下文中一共展示了NamedPipeClientStream.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendCommandToCore
public static bool SendCommandToCore(string machine, string command)
{
NamedPipeClientStream pipeClient =
new NamedPipeClientStream(machine, Kernel.MBCLIENT_MUTEX_ID,
PipeDirection.Out, PipeOptions.None);
StreamWriter sw = new StreamWriter(pipeClient);
try
{
pipeClient.Connect(2000);
}
catch (TimeoutException)
{
Logger.ReportWarning("Unable to send command to core (may not be running).");
return false;
}
try
{
sw.AutoFlush = true;
sw.WriteLine(command);
pipeClient.Flush();
pipeClient.Close();
}
catch (Exception e)
{
Logger.ReportException("Error sending commmand to core", e);
return false;
}
return true;
}
示例2: Connect
public void Connect(string pipeName, string serverName = ".", int timeout = 2000)
{
NamedPipeClientStream pipeStream = null;
try
{
pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut,
PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation);
pipeStream.Connect(timeout);
using (var stringStream = new StringStream(pipeStream))
{
if (OnConnected != null)
{
OnConnected(stringStream);
}
}
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
}
finally
{
if (pipeStream != null && pipeStream.IsConnected)
{
pipeStream.Flush();
pipeStream.Close();
}
}
}
示例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: 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();
}
示例5: Start
// Use this for initialization
void Start()
{
System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe");
clientStream.Connect (60);
byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("Connected/n");
Debug.Log ("connected");
clientStream.Write (buffer, 0, buffer.Length);
clientStream.Flush ();
clientStream.Dispose ();
clientStream.Close ();
}
示例6: SendToPipe
void SendToPipe()
{
byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("done");
System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe");
clientStream.Connect (System.TimeSpan.MaxValue.Seconds);
clientStream.WaitForPipeDrain();
clientStream.Write (buffer, 0, buffer.Length);
clientStream.Flush ();
clientStream.Dispose();
clientStream.Close();
}
示例7: Send
public bool Send(string pipeName, string message) {
bool bSuccess = true;
using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) {
try {
pipeStream.Connect(CONNECT_TIMEOUT);
pipeStream.ReadMode = PipeTransmissionMode.Message;
byte[] cData = Encoding.UTF8.GetBytes(message);
pipeStream.Write(cData, 0, cData.Length);
pipeStream.Flush();
} catch(Exception __errExcep) {
if (logger.IsErrorEnabled) logger.ErrorFormat("{0}\r\n{1}", __errExcep.Message, __errExcep.StackTrace);
bSuccess = false;
}
}
return bSuccess;
}
示例8: ConnectToMasterPipeAndSendData
public static void ConnectToMasterPipeAndSendData(string data)
{
byte[] stringData = Encoding.UTF8.GetBytes(data);
int stringLength = stringData.Length;
byte[] array = new byte[sizeof(Int32) + stringLength];
using (MemoryStream stream = new MemoryStream(array))
{
byte[] stringLengthData = BitConverter.GetBytes(stringLength);
stream.Write(stringLengthData, 0, stringLengthData.Length);
stream.Write(stringData, 0, stringData.Length);
}
NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "SpeditNamedPipeServer", PipeDirection.Out, PipeOptions.Asynchronous);
pipeClient.Connect(5000);
pipeClient.Write(array, 0, array.Length);
pipeClient.Flush();
pipeClient.Close();
pipeClient.Dispose();
}
示例9: CreateWebHost
public static IWebHost CreateWebHost(HttpsConnectionFilterOptions httpsOptions) {
var webHostBuilder = new WebHostBuilder()
.UseLoggerFactory(_loggerFactory)
.UseConfiguration(Configuration)
.UseKestrel(options => {
if (httpsOptions != null) {
options.UseHttps(httpsOptions);
}
//options.UseConnectionLogging();
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>();
var webHost = webHostBuilder.Build();
var serverAddresses = webHost.ServerFeatures.Get<IServerAddressesFeature>();
string pipeName = _startupOptions.WriteServerUrlsToPipe;
if (pipeName != null) {
NamedPipeClientStream pipe;
try {
pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out);
pipe.Connect(10000);
} catch (IOException ex) {
_logger.LogCritical(0, ex, Resources.Critical_InvalidPipeHandle, pipeName);
throw;
} catch (TimeoutException ex) {
_logger.LogCritical(0, ex, Resources.Critical_PipeConnectTimeOut, pipeName);
throw;
}
var applicationLifetime = webHost.Services.GetService<IApplicationLifetime>();
applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => {
using (pipe) {
string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses);
_logger.LogTrace(Resources.Trace_ServerUrlsToPipeBegin, pipeName, Environment.NewLine, serverUriStr);
var serverUriData = Encoding.UTF8.GetBytes(serverUriStr);
pipe.Write(serverUriData, 0, serverUriData.Length);
pipe.Flush();
}
_logger.LogTrace(Resources.Trace_ServerUrlsToPipeDone, pipeName);
}));
}
return webHost;
}
示例10: SendMessageAsync
public static Task<bool> SendMessageAsync(object message, string pipeName, bool wait = true)
{
return Task.Run<bool>(new Func<bool>(() =>
{
try
{
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.None))
{
using (MemoryStream ms = new MemoryStream())
{
if (wait)
{
int i = 0;
for (; i != 20; i++)
{
if (!NamedPipeDoesNotExist(pipeName)) break;
Thread.Sleep(50);
}
if (i == 20) return false;
}
if (NamedPipeDoesNotExist(pipeName)) return false;
pipeClient.Connect(10);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, message);
ms.Seek(0, SeekOrigin.Begin);
ms.CopyTo(pipeClient);
pipeClient.Flush();
pipeClient.WaitForPipeDrain();
}
}
return true;
}
catch (Exception e)
{
Logging.LogException(e);
return false;
}
}));
}
示例11: HandleCommandLine
public static void HandleCommandLine (int connectTimeoutMs = 2500) {
var commandLineArgs = Environment.GetCommandLineArgs();
if ((commandLineArgs.Length == 3) && (commandLineArgs[1] == "--buildSolution")) {
try {
var jss = new JavaScriptSerializer {
MaxJsonLength = 1024 * 1024 * 64
};
var pipeId = commandLineArgs[2];
using (var pipe = new NamedPipeClientStream(pipeId)) {
pipe.Connect(connectTimeoutMs);
using (var sr = new StreamReader(pipe))
using (var sw = new StreamWriter(pipe)) {
var argsJson = sr.ReadLine();
var argsDict = jss.Deserialize<Dictionary<string, object>>(argsJson);
var buildResult = Build(
(string)argsDict["solutionFile"],
(string)argsDict["buildConfiguration"],
(string)argsDict["buildPlatform"],
(string)argsDict["buildTarget"],
(string)argsDict["logVerbosity"],
true
);
var resultJson = jss.Serialize(buildResult);
sw.WriteLine(resultJson);
sw.Flush();
pipe.Flush();
pipe.WaitForPipeDrain();
}
}
} catch (Exception exc) {
Console.Error.WriteLine(exc.ToString());
Environment.Exit(1);
}
Environment.Exit(0);
}
}
示例12: 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;
}
}
}
示例13: Send
private void Send(string message)
{
try
{
if (string.IsNullOrWhiteSpace(message))
return;
using (var pipeStream = new NamedPipeClientStream
(".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous))
{
pipeStream.Connect(Timeout*1000);
var buffer = Encoding.UTF8.GetBytes(message);
pipeStream.Write(buffer, 0, buffer.Length);
pipeStream.Flush();
pipeStream.WaitForPipeDrain();
}
}
catch (Exception e)
{
Log.WarnFormat("An exception occurred while trying to send '{0}' to pipe '{1}': {2}", Message, PipeName, e.Message);
}
}
示例14: BCLSystemIOPipeClient
const int BUFFER_SIZE = 1024; // 1 KB
#endregion Fields
#region Methods
static void BCLSystemIOPipeClient()
{
/////////////////////////////////////////////////////////////////////
// Try to open a named pipe.
//
// Prepare the pipe name
String strServerName = ".";
String strPipeName = "HelloWorld";
NamedPipeClientStream pipeClient = null;
try
{
pipeClient = new NamedPipeClientStream(
strServerName, // The server name
strPipeName, // The unique pipe name
PipeDirection.InOut, // The pipe is bi-directional
PipeOptions.None, // No additional parameters
//The server process cannot obtain identification information about
//the client, and it cannot impersonate the client.
TokenImpersonationLevel.Anonymous);
pipeClient.Connect(60000); // set TimeOut for connection
pipeClient.ReadMode = PipeTransmissionMode.Message;
Console.WriteLine(@"The named pipe, \\{0}\{1}, is connected.",
strServerName, strPipeName);
/////////////////////////////////////////////////////////////////
// Send a message to the pipe server and receive its response.
//
// A byte buffer of BUFFER_SIZE bytes. The buffer should be big
// enough for ONE request to the client
string strMessage;
byte[] bRequest; // Client -> Server
int cbRequestBytes;
byte[] bReply = new byte[BUFFER_SIZE]; // Server -> Client
int cbBytesRead, cbReplyBytes;
// Send one message to the pipe.
// '\0' is appended in the end because the client may be a native
// C++ program.
strMessage = "Default request from client\0";
bRequest = Encoding.Unicode.GetBytes(strMessage);
cbRequestBytes = bRequest.Length;
if (pipeClient.CanWrite)
{
pipeClient.Write(bRequest, 0, cbRequestBytes);
}
pipeClient.Flush();
Console.WriteLine("Sends {0} bytes; Message: \"{1}\"",
cbRequestBytes, strMessage.TrimEnd('\0'));
// Receive one message from the pipe.
cbReplyBytes = BUFFER_SIZE;
do
{
if (pipeClient.CanRead)
{
cbBytesRead = pipeClient.Read(bReply, 0, cbReplyBytes);
// Unicode-encode the byte array and trim all the '\0' chars
// at the end.
strMessage = Encoding.Unicode.GetString(bReply).TrimEnd('\0');
Console.WriteLine("Receives {0} bytes; Message: \"{1}\"",
cbBytesRead, strMessage);
}
}
while (!pipeClient.IsMessageComplete);
}
catch (TimeoutException ex)
{
Console.WriteLine("Unable to open named pipe {0}\\{1}",
strServerName, strPipeName);
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("The client throws the error: {0}", ex.Message);
}
finally
{
/////////////////////////////////////////////////////////////////
// Close the pipe.
//
//.........这里部分代码省略.........
示例15: Main
//.........这里部分代码省略.........
var xml = XElement.Parse(
Encoding.UTF8.GetString(buffer, 0, c)
);
var old = new { Console.ForegroundColor };
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(new { xml });
Console.ForegroundColor = old.ForegroundColor;
// do something with incoming params?
pipeServer.Disconnect();
// server inactive for a moment, update the state and reconnect to next client
InternalMain(
xml.Elements().Select(x => x.Value).ToArray()
);
}
}
var wConnected = false;
new Thread(
delegate ()
{
// allow 100 until we need to take action
Thread.Sleep(100);
if (wConnected)
{
// server already active!
return;
}
AsServerSignal.Set();
// make us a new server
// cmd.exe allows us to survive a process crash.
Console.WriteLine("Process.Start cmd");
Process.Start("cmd.exe", "/K " + typeof(Program).Assembly.Location);
}
)
{
IsBackground = true
}.Start();
Console.WriteLine("connecting to the server...");
var w = new NamedPipeClientStream(".",
Environment.CurrentDirectory.GetHashCode() +
"foo", PipeDirection.Out, PipeOptions.WriteThrough);
Thread.Yield();
w.Connect();
wConnected = true;
Console.WriteLine("connecting to the server... done");
// http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.jmp(v=vs.110).aspx
var bytes = Encoding.UTF8.GetBytes(
new XElement("xml",
from x in args
select new XElement("arg", x)
).ToString()
);
w.Write(bytes, 0, bytes.Length);
w.Flush();
w.Dispose();
//Thread.Sleep(100);
//Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.
//1> at System.Console.ReadKey(Boolean intercept)
//1> at System.Console.ReadKey()
//Debugger.Break();
//Console.ReadKey();
}