我有一個簡單的客戶端/服務器應用程序。我嘗試從UI訪問數組列表,但返回一個空數組列表。我已經嘗試了互聯網上的所有可能的解決方案,但沒有一個適用於我的案例ArrayList在從單獨的線程訪問時被清空,儘管它被填充。
Server.java
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class Server {
public static ArrayList<MyThread> clients = new ArrayList<MyThread>();
public static void main(String args[]) throws IOException {
ServerSocket s = new ServerSocket(7777);
try {
while (true) {
Socket s1 = s.accept();
MyThread t = new MyThread(s1);
clients.add(t); // adds threads to an ArrayList
System.out.println(clients); // prints the ArrayList(It works and print all threads)
t.start(); //start the thread
}
} catch (SocketException e) {
System.out.println("Error: " + e);
}
}
}
這是一個MouseClickeed方法在我的UI類,我想訪問的ArrayList在服務器類
public void mouseClicked(MouseEvent arg0) {
try {
String s = textField.getText();
Client.ClientName = s; \\ gets the string entered and set it as Client Name
System.out.println(Server.clients); \\It's supposed to print Client ArrayList but instead it prints an empty List ([])
}
catch (NullPointerException e1) {
System.out.println("Error: " + e1);
}
}
});
是否已將您的客戶端連接到服務器? – haifzhan
是的,已連接並添加到列表中。這是肯定的。 –
請格式化您的代碼 - 當它沒有縮進時更難閱讀。 (這顯然不是你真正的代碼,因爲斜槓是倒退的......) –