我有一个简单的客户端/服务器应用程序。我尝试从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
是的,已连接并添加到列表中。这是肯定的。 –
请格式化您的代码 - 当它没有缩进时更难阅读。 (这显然不是你真正的代码,因为斜杠是倒退的......) –