我有一个服务器和客户端代码。在我的服务器上,我正在等待连接并创建两个线程(现在只有两个客户端)。这是我的服务器代码片段。将不同的值传递给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。而已。