I am implementing a tcp java client/server app based on a tut on the internet
I changed some methods and get error of nullpointerexception
The error comes from the run(). Its in a Connection class that extends the Thread class. run() is supposed to listen to incoming communication. I start the server class, listen to a port. So I have a succefful connection. Then the app reports error when I try to listen to incoming communication through the run() method
establish a connection and start:
Connection c = new Connection(host,port);
Scanner chatConsole = new Scanner(System.in);
String text = "";
while (!text.equalsIgnoreCase("halt")){
text = chatConsole.nextLine();
c.start();
Exception in thread “Thread-1” java.lang.NullPointerException
The run()
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);
}
}
This is the constructor for the class if its helpful to debug.
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);
}
}
Thank you
Your
invariable is null, where you try to use it:possibly because you’re shadowing it where you construct it.
Instead don’t re-declare the variable locally: