ZKTservice

在 .NET Framework 中,你可以使用 System.Net.Sockets 命名空间下的 Socket 类来实现同时捕获多个客户端的信息。以下是一个示例代码:

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

class ZKPOSIDServer
{
    static void Main()
    {
        StartListening("192.168.10.5", 16980);
        StartListening("192.168.10.6", 16980);
        StartListening("192.168.10.9", 16980);

        // 阻止主线程退出
        Console.ReadLine();
    }

    static void StartListening(string ipAddress, int port)
    {
        IPAddress localAddress = IPAddress.Parse(ipAddress);
        IPEndPoint localEndPoint = new IPEndPoint(localAddress, port);

        // 创建监听 socket
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(localEndPoint);
        listener.Listen(10);

        Console.WriteLine($"开始监听 {ipAddress}:{port} 的客户端连接...");

        Thread listenThread = new Thread(() =>
        {
            while (true)
            {
                // 阻塞并接受客户端连接
                Socket clientSocket = listener.Accept();
                ThreadPool.QueueUserWorkItem(HandleClient, clientSocket);
            }
        });

        listenThread.Start();
    }

    static void HandleClient(object clientSocketObj)
    {
        Socket clientSocket = (Socket)clientSocketObj;

        Console.WriteLine($"客户端 {clientSocket.RemoteEndPoint} 连接成功!");

        byte[] buffer = new byte[1024];

        while (true)
        {
            try
            {
                // 接收客户端数据
                int bytesRead = clientSocket.Receive(buffer);
                if (bytesRead == 0)
                {
                    break; // 客户端断开连接
                }

                string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                // 根据业务逻辑处理 message

                Console.WriteLine($"来自客户端 {clientSocket.RemoteEndPoint} 的消息:{message}");
            }
            catch (SocketException)
            {
                break; // 客户端断开连接
            }
        }

        Console.WriteLine($"客户端 {clientSocket.RemoteEndPoint} 断开连接.");
        clientSocket.Close();
    }
}

发表评论