将数据从Windows应用程序发送到控制台应用程序

3

我在应用程序中创建了一个使用Windows窗体的GUI,在该窗体中有一个具有值的ListBox和一个名为sendto的按钮。用户从ListBox中进行选择,然后点击sendto按钮。 点击此按钮时,应在控制台应用程序中显示所选ListBox值。 在这里,Windows窗体中开发的GUI充当服务器,而控制台应用程序则充当客户端。 如何在C#中从Windows窗体发送数据到控制台应用程序? 我是C#的新手。


它们会在同一台物理机器上运行吗? - Cocowalla
GUI应用程序启动控制台应用程序还是两者始终都在运行? - Antonio Bakula
1
可能对于这种简单的情况会有一点额外开销,但考虑研究一下 WCF [http://msdn.microsoft.com/en-us/library/ms735119(v=vs.90).aspx]。 - Andrey
在不同的机器客户端上,一个机器上有服务器。 - Deepu
我已经查看了你们提供的链接,但仍然没有理解。 - Deepu
2个回答

2

我正在回答你的问题:使用C#进行套接字编程...但是有些人不理解,关闭了你的问题...

我知道你可能是一个新程序员。但我发现你很擅长提问,这可以帮助你自我发展成为更好的程序员。我会投票支持你!:D

看以下代码,它将帮助你玩转迷你客户端服务器应用程序。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PostSharp.Aspects;
using System.Diagnostics;
using System.IO;

namespace TestCode
{
    public class Program
    {
        public static StreamReader ServerReader;

        public static StreamWriter ServerWriter;

        static void Main(string[] args)
        {
            // here are all information to start your mini server
            ProcessStartInfo startServerInformation = new ProcessStartInfo(@"c:\path\to\serverApp.exe");

            // this value put the server process invisible. put it to false in while debuging to see what happen
            startServerInformation.CreateNoWindow = true;

            // this avoid you problem
            startServerInformation.ErrorDialog = false;

            // this tells that you whant to get all connections from the server
            startServerInformation.RedirectStandardInput = true;
            startServerInformation.RedirectStandardOutput = true;

            // this tells that you whant to be able to use special caracter that are not define in ASCII like "é" or "ï"
            startServerInformation.StandardErrorEncoding = Encoding.UTF8;
            startServerInformation.StandardOutputEncoding = Encoding.UTF8;

            // start the server app here
            Process serverProcess = Process.Start(startServerInformation);

            // get the control of the output and input connection
            Program.ServerReader = serverProcess.StandardOutput;
            Program.ServerWriter = serverProcess.StandardInput;

            // write information to the server
            Program.ServerWriter.WriteLine("Hi server im the client app :D");

            // wait the server responce
            string serverResponce = Program.ServerReader.ReadLine();

            // close the server application if needed
            serverProcess.Kill();
        }
    }
}

请注意,在服务器应用程序中,您可以使用以下方式接收客户端信息:
string clientRequest = Console.ReadLine();
Console.WriteLine("Hi client i'm the server :) !");

1

您可以使用管道,有关本地通信,请查看MSDN文章;有关网络通信,请查看MSDN文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接