2016-11-29 31 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 
... 
相关问题