Java 我应该向构造函数发送什么类型的数组?
我正在创建一个服务器聊天客户端应用程序,并借用了代码。除了一个,我知道大多数事情是如何运作的 在我的Java 我应该向构造函数发送什么类型的数组?,java,arrays,sockets,client-server,chat,Java,Arrays,Sockets,Client Server,Chat,我正在创建一个服务器聊天客户端应用程序,并借用了代码。除了一个,我知道大多数事情是如何运作的 在我的类服务器中我等待套接字被接受 public static ArrayList<String> clientUsernameList = new ArrayList<>(); /** * @param args the command line arguments * @throws java.io.IOException */ public static void
类服务器中
我等待套接字被接受
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
}
//还有一些代码
这就是我迷路的地方。我是否发送了整个阵列?如果我这样做了,user1不应该只得到一个有1个用户的数组吗?当user2连接时,他不应该得到一个有2个用户的数组吗?我迷路了。如果有人能给我指出一些可以解释这一点的东西,我将不胜感激
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;
}