我正在创建一个应用程序,客户端可以在该应用程序中向服务器发送TCP数据包,服务器将响应。但是,当我将缓冲的数据flush()到输出流时,它会产生一个nullpointer异常。对于每个连接的新客户端,都会创建一个带有类的新线程。这是课程:
public class clientHandler implements Runnable{
private boolean loggedin = false;
private String username = "";
Socket cs;
OutputStream rawoutput; //for some reason I had to pass the outputstream directly to the constructor rather than get it here, here it would produce a npe
clientHandler(Socket clientSocket, OutputStream bos){
rawoutput = bos;
cs = clientSocket;
}
DataOutputStream output;
{
try {
output = new DataOutputStream(rawoutput);
} catch (Exception e) {
System.out.println("rip OS");
e.printStackTrace();
}
}
//a couple more methods...
private void metaData(String data) throws Exception{
if(data.startsWith("/iusername")){
String[] useful = data.split(";");
System.out.println(useful[0].split(":")[1] + " logged in");
output.writeBytes("logged in");
output.flush();
username = useful[0].split(":")[1];
loggedin = true;
}
}
}
在我编写自己的产品之前,我一直将netcat用作“客户端”。这也许是为什么会导致NPE的原因吗?我已经尝试了所有不同种类的输出流和写入器,它们在初始化,写入或刷新时都会产生错误。
答案 0 :(得分:0)
感谢用户John Skeet,我修复了该错误。问题是我在初始化块中没有实现输出DataOutputStream。因此,要解决此问题,我只需要将其移至run()函数即可,现在一切正常。