在一个项目中如何设置“客户端”控制台应用程序和“服务器”控制台应用程序

时间:2016-01-26 22:17:15

标签: c#

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

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

此外,我不知道如何在C#类型的项目中进行设置。

1 个答案:

答案 0 :(得分:3)

要获得完整的教程,我建议您阅读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文件,先运行服务器,然后再运行客户端。您应该在服务器和客户端控制台窗口上看到一些输出。

编辑:请记住,这将使您在本地运行服务器和客户端。当您将服务器/客户端代码分发到其他计算机时,您将不得不应对防火墙,端口转发和可能的代理,具体取决于您的网络。