2016-11-29 28 views
0

我有一個服務器和客戶端代碼。在我的服務器上,我正在等待連接並創建兩個線程(現在只有兩個客戶端)。這是我的服務器代碼片段。將不同的值傳遞給java網絡中的線程?

while (true) { 
      try { 
       Socket client = server.accept(); 
       int i; 
       for (i = 0; i < 2; i++) { 
        if(threads[i] == null) { 
         (threads[i] = new ClientThread(client, threads, i + 1)).start(); 
         break; 
        } 
       } 
       if(i == 2) { 
        PrintStream os = new PrintStream(client.getOutputStream()); 
        os.println("Server too busy. Try later."); 
        os.close(); 
        client.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

在我的ClientThread類中,我有這個構造函數和run方法。

public ClientThread(Socket sock, ClientThread[] threads, int count) { 
      this.clientSocket = sock; 
      this.threads = threads; 
      this.count = count; 
     } // end constructor 

     public void run() { 
      ClientThread[] threads = this.threads; 

      try { 
       is = new DataInputStream(clientSocket.getInputStream()); 
       os = new DataOutputStream(clientSocket.getOutputStream()); 
       os.writeUTF("Hello client"+count); 
       System.out.println("Client sent =>"+ is.readUTF()); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      for (int i = 0; i < 2; i++) { 
       if (threads[i] == this) { 
        threads[i] = null; 
       } 
       } 

      try { 
       is.close(); 
       os.close(); 
       clientSocket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } // end run method 

我運行的服務器,並且當客戶端獲取連接,客戶端接收一些串(同計數一起),這被打印出來。現在另一個客戶端也應該連接並獲得增加的計數。但是當我運行我的代碼時,服務器啓動,即使我運行兩個客戶端,我仍然只獲得1作爲對應於count的輸出,而不是第一個客戶端爲1,第二個客戶端爲2。 我哪裏錯了?

編輯: 我的客戶端是一個簡單的套接字代碼,它讀取utf並寫入utf。而已。

回答

0

我認爲你的程序是正確的。試圖找出爲什麼輸出是這樣的。

想想這種情況下,之前,服務器接受由第二客戶端發送的數據:

Socket client = server.accept(); 

第一個客戶(假設它作爲線程的線程[0]根據您的代碼)已完成其工作,這意味着你分配null線程[0]:

for (int i = 0; i < 2; i++) { 
    if (threads[i] == this) { 
     threads[i] = null; 
    } 
} 

此過程完成後,服務器嘗試接受發送的數據第二客戶端,以便在循環:

for (i = 0; i < 2; i++) { 
    if(threads[i] == null) { 
     (threads[i] = new ClientThread(client, threads, i + 1)).start(); 
     break; 
    } 
} 

thread[0]仍然nullcount仍然是1,你仍然會得到了1作爲輸出。

建議: 如果你想多線程同時工作,就可以改變你的代碼:

... 
is = new DataInputStream(clientSocket.getInputStream()); 
os = new DataOutputStream(clientSocket.getOutputStream()); 
os.writeUTF("Hello client"+count); 
System.out.println("Client sent =>"+ is.readUTF()); 
TimeUnit.MILLISECONDS.sleep(100);// Add this line to simulate working 
... 
相關問題