发送消息给其他进程

时间:2013-07-15 05:50:00

标签: c# wpf inter-process-communicat

我希望能够在服务器应用程序和客户端应用程序之间进行通信。这两个应用程序都是用C#/ WPF编写的。接口位于一个单独的DLL中,两个应用程序都有一个引用它。

在interface-dll中是IDataInfo-Interface,它看起来像:

public interface IDataInfo
    {
        byte[] Header { get; }
        byte[] Data { get; }
    }

Server-Application通过以下代码调用客户端:

Serializer<IDataInfo> serializer = new Serializer<IDataInfo>();
IDataInfo dataInfo = new DataInfo(HEADERBYTES, CONTENTBYTES);
Process clientProcess = Process.Start("Client.exe", serializer.Serialize(dataInfo));

客户端应用程序通过以下方式从服务器获取消息:

Serializer<IDataInfo> serializer = new Serializer<IDataInfo>();
IDataInfo dataInfo = serializer.Deserialize(string.Join(" ", App.Args));

Serializer-Class只是一个使用Soap-Formatter序列化/反序列化的泛型类。代码如下:

public class Serializer<T>
{
    private static readonly Encoding encoding = Encoding.Unicode;

    public string Serialize(T value)
    {
        string result;
        using (MemoryStream memoryStream = new MemoryStream())
        {
            SoapFormatter soapFormatter = new SoapFormatter();
            soapFormatter.Serialize(memoryStream, value);
            result = encoding.GetString(memoryStream.ToArray());
            memoryStream.Flush();
        }
        return result;
    }

    public T Deserialize(string soap)
    {
        T result;
        using (MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(soap)))
        {
            SoapFormatter soapFormatter = new SoapFormatter();
            result = (T)soapFormatter.Deserialize(memoryStream);
        }
        return result;
    }
}

直到这里一切正常。服务器创建客户端,客户端可以将其参数反序列化为IDataInfo - Object。

现在我希望能够从服务器向正在运行的客户端发送消息。我使用方法void ReceiveMessage(string message);

在Interface-DLL中引入了IClient-Interface

MainWindow.xaml.cs正在实现IClient-Interface。

我现在的问题是,当我拥有Process-Object时,如何在服务器中获取IClient-Object。我想过Activator.CreateInstance,但我不知道如何做到这一点。我很确定我可以通过Process的Handle获得IClient,但我不知道如何。

有什么想法吗?

3 个答案:

答案 0 :(得分:4)

正如其他帖子提到的一样,常见的方法是创建服务, 也让它更简单我会考虑ServiceStack。 AFAIK ServiceStack用于stackoverflow

pluralsight

上还有关于它的课程

ServiceStack非常容易在任何.net dll中托管(没有iis等),并且没有WCF的配置复杂性。

此外,端点可用作SOAP和REST,无需配置任何内容

例如,这定义了一个hello world服务

public class HelloService : IService<Hello>
{
    public object Execute(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
}

这是客户端代码的示例:

var response = client.Send<HelloResponse>(new Hello { Name = "World!" });
Console.WriteLine(response.Result); // => Hello, World

你可以找到更多 复杂的例子和演练:ServiceStack.Hello

答案 1 :(得分:1)

多处理之间的通信有很多可以实现的。 像socket,fileMapping,共享内存,windows 32消息等。

也许样本方式是你可以使用WCF。

答案 2 :(得分:0)

有许多方法可以进行进程间通信,
但如果您正在寻找快速简便的解决方案,您可能需要查看ZeroMQ WCF也是一种选择,但在你的情况下它可能有点过分。

您可以在此处找到有关ZeroMQ的更多信息:http://www.zeromq.org/ 您可以使用NuGet将其安装到项目中。

serverclient的简短示例:

服务器侦听连接,需要一个字符串,反转字符串并返回它:

public class Server
{
    public Server()
    {

    }

    public void Listen()
    {
        Task.Run(() =>
        {
            using (var context = new Context())
            {
                //Open a socket to reply
                using (var socket = context.Socket(SocketType.REP))
                {
                    socket.Bind("tcp://127.0.0.1:32500");
                    while (true)
                    {
                        //Again you could also receive binary data if you want
                        var request = socket.Recv(Encoding.UTF8);
                        var response = ReverseString(request);
                        socket.Send(response, Encoding.UTF8);
                    }
                }
            }
        });
    }

    private string ReverseString(string request)
    {
        var chars = request.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
}

客户端连接到服务器(在本例中为同一台机器):

public class Client
{
    public Client()
    {

    }

    public string ReverseString(string message)
    {
        using (var context = new Context())
        {
            //Open a socket to request data
            using (var socket = context.Socket(SocketType.REQ))
            {
                socket.Connect("tcp://127.0.0.1:32500");

                //Send a string, you can send a byte[] as well, for example protobuf encoded data
                socket.Send(message, Encoding.UTF8);

                //Get the response from the server
                return socket.Recv(Encoding.UTF8);
            }
        }
    }
}

要测试它,程序可能如下所示:

public class Program
{
    public static void Main()
    {
        new Program();
    }

    public Program()
    {
        var server = new Server();
        server.Listen();

        var client = new Client();

        var input = String.Empty;

        while (input != "/quit")
        {
            input = Console.ReadLine();
            Console.WriteLine(client.ReverseString(input));
        }
    }

}

这很容易,它完成了工作。

另一种方法是使用IPC的命名管道:http://www.codeproject.com/Tips/492231/Csharp-Async-Named-Pipes

相关问题