检查NamedPipeServerStream是否在客户端启动的方法

时间:2015-08-06 06:14:41

标签: c# pipe namedpipeserverstream

我有一个使用NamedPipeClientStream的客户端和一个使用NamedPipeServerStream的服务器。

客户端可以在服务器之前启动,当它调用clientStream.Connect(timeout)时,我会按预期获得TimeoutException。

在调用Connect以防止异常之前,有没有办法检查是否有NamedPipeServerStream监听?

3 个答案:

答案 0 :(得分:2)

我建议您使用EventWaitHandle。在所有客户端上,打开流后调用WaitOne()并在服务器上调用Set()。

所以,在“服务器”端,写下这个:

EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset, String.Format(@"Global\{0}", "SERVER_OPENED_HANDLE"));

OpenStream (); // inside this method you would have code that opens your named pipe for incomming messages

// finally, signal that you are done

handle.Set ();

在客户端,写下这样的内容:

EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset, String.Format(@"Global\{0}", "SERVER_OPENED_HANDLE"));

// here your thread will sleep until the server calls "Set"
handle.WaitOne ();

// then you can safelly connect to the server here

ConnectToServer ();

还有一些情况需要处理:

1)管道无法在服务器上打开,因为已经打开了一个具有相同名称的管道(将引发异常)。

2)您成功打开了管道,您已通知客户您已准备就绪,但在此之后的几毫秒之后,服务器因某些意外原因而崩溃,客户端无法访问服务器。

3)用户权限问题

在所有这些情况下,您应该使用try / catch处理这些异常,通常,如果一切顺利,此代码将确保客户端在服务器成功打开管道之前不会尝试连接。

无论如何,我建议使用更先进的技术通过命名管道进行IPC,例如使用WCF甚至.NET Remoting,除了它被某些人认为过时(不包括我)这个事实至少是非常体面的用于IPC通信。这将为您提供自由和可扩展性(可能有一天您需要您的客户能够驻留在其他计算机上,您将不得不从IPC切换到LAN通信,甚至在WAN / Internet中)。

答案 1 :(得分:1)

无法仅使用$("[id=$txtCiStartDate]").datepicker()进行检查。但是,您可以使用NamedPipeClientStream之类的

Mutex

您可能希望将// In the server var mutex = new System.Threading.Mutex(false, "MyPipeMutex"); OpenPipeAndRunServer(); mutex.Close(); // In the client process var mutex = new System.Threading.Mutex(false, "MyPipeMutex"); if (!mutex.WaitOne(0, false)) { OpenPipe(); } mutex.Close(); 调用包装在try-finally块中,以确保它始终关闭。在客户端中,您可以使用不同的超时来实际等待打开NamedPipe。

您还可以将异常作为解决方法来捕获。

答案 2 :(得分:0)

如果五年后有人遇到这个问题,这可能会有所帮助:

<?php
if (isset($_POST)) {
    $mail = $_POST['mail'];
    if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
        $data = ['success' => false, 'message' => 'invalid email'];
    } else {
        $data = ['success' => true, 'message' => 'correct data'];
    }
    echo json_encode($data);
}