我有一個服務器和客戶端代碼。在我的服務器上,我正在等待連接並創建兩個線程(現在只有兩個客戶端)。這是我的服務器代碼片段。將不同的值傳遞給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。而已。