【问题标题】:In a project how to set up a "client" console application and a "server" console application在项目中如何设置“客户端”控制台应用程序和“服务器”控制台应用程序
【发布时间】:2016-01-27 06:40:12
【问题描述】:

好的,所以这可能是措辞错误或使用了错误的术语。我想知道如何在我的本地机器上设置一个控制台应用程序,它是“服务器”,它将运行我在客户端窗口上发生的所有后台任务/事件?我将只有一个用于“服务器”的控制台应用程序和最多四个“客户端”控制台应用程序。

这些中的每一个都会做不同的事情。 “服务器”应用程序只会执行所有计算和功能,客户端只会以漂亮的格式显示我希望它们从服务器结果中显示的内容。

我也不知道如何在 C# 类型的项目中设置它。

【问题讨论】:

  • 您是在问如何在不同的机器上安装和运行客户端/服务器应用程序,还是在问如何对它们进行编码?
  • @Chase 对它们进行编码并将它们“连接”在一起,以便我可以在一个 IDE 项目中使用它们。
  • 听起来 MVVW/WPF 或 MVC 可能会出现在你的未来。

标签: c#


【解决方案1】:

对于完整的教程,我建议阅读this Code Project article

对于一些示例代码,以下客户端/服务器控制台应用程序是从 MSDN 中提取的。

Synchronous Client Socket Example:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient {

    public static void StartClient() {
        // Data buffer for incoming data.
        byte[] bytes = new byte[1024];

        // Connect to a remote device.
        try {
            // Establish the remote endpoint for the socket.
            // This example uses port 11000 on the local computer.
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork, 
                SocketType.Stream, ProtocolType.Tcp );

            // Connect the socket to the remote endpoint. Catch any errors.
            try {
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}",
                    sender.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.
                byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

                // Send the data through the socket.
                int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("Echoed test = {0}",
                    Encoding.ASCII.GetString(bytes,0,bytesRec));

                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            } catch (ArgumentNullException ane) {
                Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
            } catch (SocketException se) {
                Console.WriteLine("SocketException : {0}",se.ToString());
            } catch (Exception e) {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

        } catch (Exception e) {
            Console.WriteLine( e.ToString());
        }
    }

    public static int Main(String[] args) {
        StartClient();
        return 0;
    }
}

Synchronous Server Socket Example:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketListener {

    // Incoming data from the client.
    public static string data = null;

    public static void StartListening() {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the 
        // host running the application.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp );

        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
        try {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            while (true) {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                data = null;

                // An incoming connection needs to be processed.
                while (true) {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes,0,bytesRec);
                    if (data.IndexOf("<EOF>") > -1) {
                        break;
                    }
                }

                // Show the data on the console.
                Console.WriteLine( "Text received : {0}", data);

                // Echo the data back to the client.
                byte[] msg = Encoding.ASCII.GetBytes(data);

                handler.Send(msg);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

    public static int Main(String[] args) {
        StartListening();
        return 0;
    }
}

要进行此设置,您需要在 Visual Studio 中创建一个新解决方案,然后向该解决方案添加两个 console application 项目,一个用于客户端,一个用于服务器。完成两个项目后,您可以复制并安装上面提供的代码。构建解决方案,为客户端和服务器生成一个.exe 文件。找到您的.exe 文件,首先运行服务器,然后再运行客户端。您应该会在服务器和客户端控制台窗口上看到一些输出。

编辑:请记住,这将使您在本地运行服务器和客户端。当您将服务器/客户端代码分发到其他机器时,您将不得不根据您的网络与防火墙、端口转发和潜在的代理进行竞争。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 2017-04-16
    • 2010-11-04
    • 1970-01-01
    • 2021-01-27
    相关资源
    最近更新 更多