不同基于 C# 的服务之间的通信 [英] Communication between different C# based services

查看:48
本文介绍了不同基于 C# 的服务之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在两个不同的服务之间进行通信?我有一个已经运行的服务.有没有办法创建可以附加到第一个服务并向其发送和接收日期的第二个服务?

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?

我还想从控制台应用程序访问 Windows 服务并附加到它.可能吗?

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

推荐答案

一开始我会尝试使用 tcpclient 和 tcpserver

To begin with I would play around with tcpclient and tcpserver

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspxhttp://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.

如果服务在不同的机器上运行,socks 也能工作,而共享内存和命名管道则不能.

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

示例代码

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

这篇关于不同基于 C# 的服务之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆