我有一個Windows服務和一個GUI,需要相互溝通。任何時候都可以發送消息。我看着使用NamedPipes,但似乎你不能讀&同時寫入流(或者至少我不能找到涵蓋這種情況下的任何示例)。與Windows命名管道(.Net)異步雙向通信
是否可以通過單個NamedPipe進行這種雙向通信? 還是需要打開兩個管道(一個來自GUI->服務,另一個來自服務 - > GUI)?
我有一個Windows服務和一個GUI,需要相互溝通。任何時候都可以發送消息。我看着使用NamedPipes,但似乎你不能讀&同時寫入流(或者至少我不能找到涵蓋這種情況下的任何示例)。與Windows命名管道(.Net)異步雙向通信
是否可以通過單個NamedPipe進行這種雙向通信? 還是需要打開兩個管道(一個來自GUI->服務,另一個來自服務 - > GUI)?
使用WCF,你可以使用命名管道雙工
// Create a contract that can be used as a callback
public interface IMyCallbackService
{
[OperationContract(IsOneWay = true)]
void NotifyClient();
}
// Define your service contract and specify the callback contract
[ServiceContract(CallbackContract = typeof(IMyCallbackService))]
public interface ISimpleService
{
[OperationContract]
string ProcessData();
}
實現服務
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class SimpleService : ISimpleService
{
public string ProcessData()
{
// Get a handle to the call back channel
var callback = OperationContext.Current.GetCallbackChannel<IMyCallbackService>();
callback.NotifyClient();
return DateTime.Now.ToString();
}
}
主機服務
class Server
{
static void Main(string[] args)
{
// Create a service host with an named pipe endpoint
using (var host = new ServiceHost(typeof(SimpleService), new Uri("net.pipe://localhost")))
{
host.AddServiceEndpoint(typeof(ISimpleService), new NetNamedPipeBinding(), "SimpleService");
host.Open();
Console.WriteLine("Simple Service Running...");
Console.ReadLine();
host.Close();
}
}
}
創建客戶端應用程序,在這個例子中,客戶端類實施回叫合同。
class Client : IMyCallbackService
{
static void Main(string[] args)
{
new Client().Run();
}
public void Run()
{
// Consume the service
var factory = new DuplexChannelFactory<ISimpleService>(new InstanceContext(this), new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/SimpleService"));
var proxy = factory.CreateChannel();
Console.WriteLine(proxy.ProcessData());
}
public void NotifyClient()
{
Console.WriteLine("Notification from Server");
}
}
感謝您的詳細回覆。我已經用這種方法,因爲它比使用2個命名管道更簡單。 – 2013-05-08 08:59:13
我也發現這非常詳細和有用的:http://idunno.org/archive/2008/05/29/wcf-callbacks-a-beginners-guide.aspx – 2013-05-08 09:31:32
任何想法,我可以讓Windows服務運行良好,但不能在嘗試添加服務引用時找到服務我得到'net.pipe:// localhost/service1'。 從管道讀取時發生錯誤:管道已結束。 (109,0x6d)。 – 2014-07-29 00:51:28
您的命名管道流類(服務器或客戶端)必須使用InOut的PipeDirection構造。您需要一個NamedPipeServerStream,可能在您的服務中,它可以由任意數量的NamedPipeClientStream對象共享。使用管道名稱和方向構建NamedPipeServerStream,使用管道名稱,服務器名稱和PipeDirection構建NamedPipeClientStream,並且應該很好。
使用單個點累積消息(在這種情況下,單個管道)也會強制您自己處理消息的方向(除此之外,還必須使用系統範圍的管道鎖)。
因此,使用2個方向相反的管道。
(另一種選擇是使用2個MSMQ隊列)。
你可以使用WCF雙工了NamedPipes,我用這個方法對我的服務/應用程序通信,這裏有一個很好的例子,可能help.http://tech.pro/tutorial/855/wcf-tutorial- basic-interprocess-communication – 2013-05-08 04:51:07