如何使用参数调用现有类?

时间:2016-11-17 01:57:17

标签: c# multithreading class search server

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

我的问题是如何从另一个类向指定的客户端发送数据? 这是我在ServerMain Class中的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可以做到(我想),但我怎么从外面打电话呢?

1 个答案:

答案 0 :(得分:0)

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