[英]nullpointer exception for thread
我正在基于互联网上的tut实现一个tcp java客户端/服务器应用程序我改变了一些方法并得到nullpointerexception的错误
错误来自run()。 它在一个扩展Thread类的Connection类中。 run()应该监听传入的通信。 我启动服务器类,听一个端口。 所以我有一个成功的联系。 然后,当我尝试通过run()方法侦听传入通信时,应用程序报告错误
建立连接并开始:
Connection c = new Connection(host,port);
Scanner chatConsole = new Scanner(System.in);
String text = "";
while (!text.equalsIgnoreCase("halt")){
text = chatConsole.nextLine();
c.start();
线程“Thread-1”中的异常java.lang.NullPointerException
运行()
public void run(){//watch for incoming communication
String msg;
try{//loop reading lines and display msg
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
}catch (IOException e) {
System.err.println(e);
}
}
如果它有助于调试,那么这是该类的构造函数。
public Connection(String iniName, int iniPort){
host = iniName;
port = iniPort;
try {
server = new Socket(host, port);
}catch (UnknownHostException e){
System.err.println(e);
System.exit(1);
}
try{
stdIn = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(server.getOutputStream(), true); //output stream to server
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
}catch(Exception e){
System.err.println(e);
}
}
谢谢
您的in
变量为null,您尝试使用它:
while ((msg = in.readLine()) != null) {
可能是因为你正在构建它的地方遮蔽它。
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
而不是在本地重新声明变量:
in = new BufferedReader(new InputStreamReader(server.getInputStream()));
无处在你的代码粘贴好你声明一个全局场in
。 这是抛出NullPointerException
吗? ( in.readLine
)。 请确保正确初始化Stream(即将其设为字段,而不是构造函数中的局部变量)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.