Communication between different C# based services

跟風遠走 提交于 2019-12-22 08:06:44

问题


Is there a way to communicate between two different services? I have a service that already runs. Is there a way to create a second service that can attach to the first service and send and receive dates to it?

I would also like to access the Windows service from a console application and attach to it. Is it possible?


回答1:


To begin with I would play around with tcpclient and tcpserver

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx

Even if the data you need to send is more complex than a date it can easily be serialized/deserialized.

For sending and receiving dates this seams the simplest option.

Also socks work if the services run on different machines whereas shared memory and namedpipes don't.

example code

// Create a thread running this code in your onstarted method of the service

using System.IO;
using System.Net;
using System.Net.Sockets;

var server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8889);
server.Start();

while(true) {
  var client = server.AcceptTcpClient(); 

  using(var sr = new StreamReader(client.GetStream())) {
    var date = DateTime.Parse(sr.ReadToEnd());
    Console.WriteLine(date);
  } 
}

// In the console

using System.IO;
using System.Net;
using System.Net.Sockets;

var client = new TcpClient("localhost",8889); 
using(var sw = new StreamWriter(client.GetStream())) {
  sw.Write(System.DateTime.Now);
}



回答2:


You can try to implement this by using:

  • IPC (Inter Process Communication via Named pipes)
  • Shared memory (Memory mapped files)
  • Socket (TCP/IP)

Example of using WCF: Many to One Local IPC using WCF and NetNamedPipeBindin.

Other example: A C# Framework for Interprocess Synchronization and Communication.

Everything depends on what version of .NET Framework you use. If you use .NET 3.0 and above then you can take a look into WCF. If not then you are on your own and you can google on keywords P/Invoke (CreateFileMapping, MapViewOfFile, CreatePipe...).



来源:https://stackoverflow.com/questions/5486917/communication-between-different-c-sharp-based-services

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