Best way to send and receive messages between a Windows service and form application

耗尽温柔 提交于 2019-12-11 23:04:18

问题


I'm attempting to implement IPC, but what I'm doing is somewhat different from the documentation I've seen.

I need to asynchronously send, receive, and respond with a service and form application.

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

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

I believe this sets up both sides.

To write from one to the other:

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

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

... and to read:

//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)
    {

    }
}

Am I in the right direct? Is there another (better) way to communicate between a Windows service and a form application?


回答1:


since you're in .NET I guess you should look into WCF - Windows Communication Foundation, you define the contracts (Service contract, data contracts), publish the service and use the service without worrying about the protocol since you can choose it by configuring the server and the client app.

You can take a look at these links for some in information:

  • http://www.codeproject.com/Articles/29243/A-Windows-Communication-Foundation-WCF-Overview
  • http://msdn.microsoft.com/en-us/library/ee958158.aspx

Hope it helps, Cheers



来源:https://stackoverflow.com/questions/18305650/best-way-to-send-and-receive-messages-between-a-windows-service-and-form-applica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!