在Windows服务和表单应用程序之间发送和接收消息的最佳方法

时间:2013-08-19 02:33:04

标签: .net forms service stream ipc

我正在尝试实施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服务和表单应用程序之间进行通信?

1 个答案:

答案 0 :(得分:1)

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

您可以查看以下链接以获取信息:

希望它有所帮助, 干杯

相关问题