Bl *_*l H 0 java sockets nullpointerexception
所以我有一个聊天室,它曾经工作,但我稍微改变了代码,尝试了一些东西,但它们没有用,所以我试图恢复原来的代码,但我不确定我做错了什么因为现在它抛出一个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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
好的,所以我不再收到错误,但现在我似乎无法发送消息.如果我从客户端发送消息,则没有错误,但消息不会显示在任一客户端上.
你得到一个NullPointerException
抛出,因为你正在尝试取消引用(即在调用方法,或阅读领域),一个变量,它是null
.
在这种情况下,很明显listWriters
是null(因为它是在发生异常的行上解除引用的唯一变量 - 查找.
字符).由于这是在你的listen()
方法中分配的,如果你在调用showAll()
之前调用,我猜你会得到这个错误listen()
.
一个非常简单的字段是listWriters
在其声明中分配一个空列表,这样它就永远不会为空:
private List<PrintWriter> listWriters = new ArrayList<PrintWriter>();
Run Code Online (Sandbox Code Playgroud)
根据应用程序的并发性要求,您可能需要做一些更复杂的事情,尽管一般原则是您必须listWriters
在尝试从中读取之前进行初始化.
归档时间: |
|
查看次数: |
2607 次 |
最近记录: |