What's the easiest way to communicate between

2020-08-01 05:42发布

There are two independent projects A and B(you have their source code) on the same machine, both can be compiled to EXE file. When A is running there is an instance of some class, let's say a, we want its data in B when running. What's the easiest way? An interview question and my answer is: serialize it and de-serialize in B. But the interviewer is not satisfied with this answer because he told me "it can be easier". At last I gave up because I don't have any better solution. What's your ideas?

3条回答
神经病院院长
2楼-- · 2020-08-01 06:09

A little bit late but you can do this ...

cannot be easier

Server code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var i = 0;
            while(true)
            {
                Console.WriteLine(Console.ReadLine() + " -> " + i++);
            }
        }
    }
}

Client Code

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.FileName = "Server.exe";
            p.Start();

            var t = new Thread(() => { while (true) { Console.WriteLine(p.StandardOutput.ReadLine()); }});
            t.Start();

            while (true)
            {
                p.StandardInput.WriteLine(Console.ReadLine());
            }
        }
    }
}
查看更多
再贱就再见
4楼-- · 2020-08-01 06:21

I think using NamedPipes (System.IO.Pipes) NamedPipeServerStream would work better in this case.

查看更多
登录 后发表回答