所以我有一个聊天室,它曾经可以工作,但我稍微更改了代码以尝试一些事情但它们没有工作,所以我试图恢复到我的原始代码,但我不确定我做错了什么,因为现在它正在抛出 NullPointerException。我的代码有一个 PrintWriters 的 ArrayList 和一个 showAll() 方法,正如它所说的那样;向聊天室中的所有人发送消息。所以基本上我想知道的是我怎么会得到例外?
//This is the main code, used to add printwriters to the arraylist and to connect to clients
//The Communicate thread is used to get input from users and use the showAll() method with that input
public void listen() {
listWriters = new ArrayList<PrintWriter>();
try {
scanner = new Scanner(System.in);
portnum = getPortNumber(scanner);
System.out.println("Listening on " + portnum);
serverSocket = new ServerSocket(portnum);
while(true) {
clientcommunicate = serverSocket.accept();
System.out.println("Connection accepted: " + clientcommunicate.toString());
PrintWriter client = new PrintWriter(clientcommunicate.getOutputStream(), true);
listWriters.add(client);
Thread t = new Thread(new Communicate(clientcommunicate));
t.start();
}
} catch (IOException ioe) {
System.err.println(ioe);
System.err.println("Error.");
System.exit(1);
}
}
//This uses a printwriter obtained in the Communicate thread; the thread initializes a socket in it with the socket obtained in the constructor
public void showAll(String msg, PrintWriter printwriter) {
for(int i = 0; i < listWriters.size(); i++) { //this is where the exception is thrown
if(!listWriters.get(i).equals(printwriter)) { //if I change the paramater listWriters.size() to a regular integer like 3, and only create 2 clients or even less, the exception is thrown here instead
listWriters.get(i).println(msg);
}
}
}
编辑:
好的,所以我不再收到错误消息,但现在我似乎无法发送消息。如果我从客户端发送消息,则没有错误,但消息不会显示在任一客户端上。