如何调用带参数的现有类

本文关键字:参数 何调用 调用 | 更新日期: 2023-09-27 18:18:22

我在我的多线程服务器上有一个名为Clients的类。

我的问题是如何从另一个类发送数据到指定的客户端?下面是ServerMain类中的Listen函数。

    public static List<Client> clients;
    public static List<Thread> threads;
    private void Listen()
    {
        clients = new List<Client>();
        threads = new List<Thread>();
        int id = 0;
        while (true)
        {
            listenerSocket.Listen(0);
            Log.Status(" Waiting for a connection...");
            var commands = new ServerCommands();
            //commands.Wait();
            Client c1 = new Client(id, listenerSocket.Accept());
            clients.Add(c1);
            Log.Status("New Client Connected!");
            Thread t = new Thread(c1.Start);
            c1.SetThread = t;
            t.Start();
            id++;
        }
    }

和我的客户端类只有一个发送示例

public class Client : IDisposable
{
    public int _id;
    public string _guid;
    public string Name;
        public Socket clientSocket;
    private Thread thread;
    public Client(int id, Socket socket)
    {
        this._id = id;
        this._guid = Guid.NewGuid().ToString();
        this.clientSocket = socket;
    }
    public Thread SetThread
    {
        set
        {
            this.thread = value;
        }
    }
    public int Id
    {
        get
        {
            return this._id;
        }
    }
            public void Receive()
    {
        byte[] buffer;
        int readBytes;
        while (clientSocket != null && clientSocket.Connected)
        {
            try
            {
                buffer = new byte[clientSocket.SendBufferSize];
                readBytes = clientSocket.Receive(buffer);
                if (readBytes > 0)
                {
                    Packet p = new Packet(buffer);
                    if (p.Type != PacketType.Disconnect)
                    {
                        new Task(() => Received(p)).Start();
                    }
                    else
                    {
                        CloseConnection();
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e);
                CloseConnection();
            }
        }
    }
    ////////// Example Send Fuction    ////////////
    private void Register(User user)
    {
        var res = Handler.RegisterDo(user);
        clientSocket.Send(res.ToBytes());
    }
}

我知道我可以像这样发送到所有已连接的客户端

        foreach(Client item in ServerMain.clients) //Client clients
        {
            Console.WriteLine(item._id);
            Console.WriteLine(item.Name);
            Console.WriteLine(item._guid);
        };

我错过了什么东西来识别吗?id可以这样做(我认为),但我如何从外部调用它?

如何调用带参数的现有类

在我对代码的理解中,您只是将'client'连接套接字包装为类客户端。您只需要将客户端类的'this.clientSocket'字段调用为send()receive() data