我正在创建一个服务器聊天客户端应用程序,并已借用了代码。我知道除了一件事情外,大多数事情是如何工作的。
在我的Class Server
中,我等待套接字被接受。
public static ArrayList<String> clientUsernameList = new ArrayList<>();
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int port = 8900; //Port number the ServerSocket is going to use
ServerSocket myServerSocket = null; //Serversocket for sockets to connect
Socket clientSocket = null; //Listerner for accepted clients
ClientThread[] clientsConnected = new ClientThread[20]; //Max clients in this server
try {
myServerSocket = new ServerSocket(port);
System.out.println("Server waiting for clients on port:" + port);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
while (true) {
try { //Freezes while-loop untill a socket have been accepted or if some failure occur
clientSocket = myServerSocket.accept();
System.out.println("Client have connected from:" + clientSocket.getLocalAddress().getHostName());
} catch (Exception e) {
//Print out exception
System.out.println(e);
}
//For-loop that counts every element in Array-clientsConnected
for (int i = 0; i < clientsConnected.length; i++) {
//If-statement checks if current element is null
if(clientsConnected[i] == null){
//If current element in the Array is null then create a new object from ClientThread class
//With a socket and the object of itself as parameter.
(clientsConnected[i] = new ClientThread(clientSocket, clientsConnected)).start();
//Must have a break otherwise it will create 20 objects (Exit for-loop)
break;
} //Exit if-statement
} //Exit for-loop
} //Exit while-loop
}
}
因此,如果套接字被接受,我将创建一个名为
Class ClientThread
的线程类要创建此类的对象,我需要一个套接字和一个数组。
这是我的ClientThread类的样子
public class ClientThread extends Thread {
private ClientThread[] clientsConnected;
private Socket SOCKET = null;
private DataInputStream IN = null;
private DataOutputStream OUT = null;
private String userName,zone;
//-------------------------------------------------------
//Constructor
public ClientThread(Socket socket, ClientThread[] clientThread) {
this.SOCKET = socket;
this.clientsConnected = clientThread;
}
//Some more code
现在这是我迷路的地方。我是否发送整个阵列?如果我这样做,则user1不应仅获得一个具有1个用户的数组,而当user2连接时,他应否获得具有2个用户的数组?我搞不清楚了。如果有人可以向我指出可以解释这一点的内容,我将不胜感激。
最佳答案
我宁愿建议您使用BlockingQueue(例如,容量有限的5)将接受的连接传递给该对象。一旦完成,您的主电源将被迫等待,直到它具有相同的空间来插入新连接,因此您将停止接受新的套接字。创建20个线程,在无限循环中尝试从该队列中获取套接字并为其提供服务。一旦完成,他们就回去等待新的请求。
因此,是的,您传递了整个数组。
关于java - 我将哪种类型的数组发送给构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28746092/