开发者

Communication between different C# based services

开发者 https://www.devze.com 2023-02-20 14:53 出处:网络
Is there a way to communicate between two different services? I have a servic开发者_StackOverflow社区e that already runs. Is there a way to create a second service that can attach to the first service

Is there a way to communicate between two different services? I have a servic开发者_StackOverflow社区e 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?


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...).


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号