2016-11-17 4 views
0

私はマルチスレッドサーバー上でクライアントと呼ばれるクラスを持っています。パラメータを使用して既存のクラスを呼び出す方法

私の質問は、指定したクライアントに別のクラスからどのようにデータを送信するのですか? ここでは、ServerMainクラスのListen関数を示します。ただ1つの送信例

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()); 
    } 
} 

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++; 
     } 
    } 

そして、私のクライアントクラス私は私がこの

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

     }; 

のようにすべての接続されたクライアントは、私が識別するために何かをしないのですに送信することができます知っていますか? idはそれを行うことができました(私は思う)が、それを外部からどのように呼び出すのですか?

答えて

0

あなたのコードを理解するには、クラスクライアントとして'client'接続ソケットをラップするだけです。クライアントクラスの'this.clientSocket'フィールドをsend()またはデータにコールするだけで済みます。

+0

はい、これはクライアントクラスのIamで動作しますが、私が知りたいのは、たとえば別のクラスのID 0のクライアントにデータを送信する方法です。 または、私はClient.SendDataTo(id、data)のようなものを呼び出すことができるように、クラス内のIDで選択したクライアント(ソケット)を変更する方法 – heizung124

+0

またはこの種のアクションを実装する方法 – heizung124

関連する問題