问题
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