0

我正在尝试实现 IPC,但我所做的与我看到的文档有些不同。

我需要使用服务和表单应用程序异步发送、接收和响应。

//Service1.cs
serverPipe = new NamedPipeServerStream(@"testpipe", PipeDirection.InOut, 
   1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

//LoginForm.cs
clientPipe = new NamedPipeClientStream(@".", @"testpipe", PipeDirection.InOut
    PipeOptions.Asynchronous);

我相信这对双方都有好处。

从一个写到另一个:

//In Service1.cs and Login.cs
private void pipeWriter()
{
    StreamWriter write = null;
    write = new StreamWriter(clientPipe);

    if (clientPipe.IsConnected)
    {
        write.Write(clientPipe);
        write.Flush();
    }
}

...并阅读:

//In Service1.cs and Login.cs
private void pipeReader()
{
    try
    {
        while (true)
        {
            using (StreamReader sr = new StreamReader(clientPipe))
            {
                string message;

                while ((message = sr.ReadLine()) != null)
                {
                    //read and respond to messages written to stream
                }
            }
        }
    }
    catch (Exception ex)
    {

    }
}

我是正确的吗?是否有另一种(更好的)方式在 Windows 服务和表单应用程序之间进行通信?

4

1 回答 1

1

因为你在 .NET 我想你应该看看 WCF - Windows Communication Foundation,你定义合同(服务合同,数据合同),发布服务并使用服务而不用担心协议,因为你可以通过配置来选择它服务器和客户端应用程序。

您可以查看这些链接以获取一些信息:

希望有帮助,加油

于 2013-08-19T07:55:41.880 回答