2011-08-17 138 views
0

我正在建立一個使用GSM/GPRS調制解調器的小型TCP/IP連接,我有一臺運行服務器(偵聽器)程序的服務器PC,並且有幾個(超過100個)調制解調器位於不同的地方,在特定的時間段內將數據包發送到服務器。TCP/IP服務器如何偵聽多個客戶端?

我已經測試過一個客戶端的系統,但是我怎樣才能用幾個客戶端來測試呢?我的服務器將如何響應多個客戶端?

這裏是我的服務器代碼:

private TcpListener tcpListener; 
    private Thread listenThread; 
    public static TcpClient client; 

    public Form1() 
    { 
     InitializeComponent(); 
     this.tcpListener = new TcpListener(IPAddress.Any, 2020); 
     this.listenThread = new Thread(new ThreadStart(ListenForClients)); 
     this.listenThread.Start(); 
    } 
    private void ListenForClients() 
    { 
     this.tcpListener.Start(); 

     while (true) 
     { 
      //blocks until a client has connected to the server 
      client = this.tcpListener.AcceptTcpClient(); 


      //create a thread to handle communication 
      //with connected client 
      Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); 
      clientThread.Start(client); 
     } 
    } 
    private void HandleClientComm(object client) 
    { 
     TcpClient tcpClient = (TcpClient)client; 
     NetworkStream clientStream = tcpClient.GetStream(); 

     //TcpClient client = new TcpClient(servername or ip , port); 
     //IpEndPoint ipend = tcpClient.RemoteEndPoint; 
     //Console.WriteLine(IPAddress.Parse(ipend.Address.ToString()); 

     //label3.Text = IPAddress.Parse(((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()).ToString(); 
     SetControlPropertyThreadSafe(label3, "Text", IPAddress.Parse(((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()).ToString()); 

     byte[] message = new byte[4096]; 
     int bytesRead; 

     while (true) 
     { 
      bytesRead = 0; 

      try 
      { 
       //blocks until a client sends a message 
       bytesRead = clientStream.Read(message, 0, 4096); 
      } 
      catch 
      { 
       //a socket error has occured 
       break; 
      } 

      if (bytesRead == 0) 
      { 
       //the client has disconnected from the server 
       break; 
      } 

      //message has successfully been received 
      ASCIIEncoding encoder = new ASCIIEncoding(); 
      //System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); 

      string received_text = encoder.GetString(message, 0, bytesRead).ToString(); 

      SetControlPropertyThreadSafe(label1, "Text", received_text); 

      if (received_text == "cmdtim") 
      { 
       SendData(DateTime.Now.ToString()); 
      } 
     } 

     tcpClient.Close(); 
    } 

正如你看到的,我創建了監聽客戶一個單獨的線程,我怎麼能聽幾個客戶呢?

我應該爲每個客戶創建一個線程嗎?
我不知道每個時候會有多少個客戶端,服務器在監聽特定客戶端時是否會緩存其他客戶端的數據?

什麼是收聽多個客戶端併發送所有數據的最佳策略?

回答

1

一些建議:

刪除:

public static TcpClient client; 

替換:

client = this.tcpListener.AcceptTcpClient(); 

TcpClient client = this.tcpListener.AcceptTcpClient(); 
相關問題