-1

I am creating a an application where a client can send TCP packets to a server and the server will respond.However, when I flush() my buffered data to an outputstream, it produces a nullpointer exception. For each new client that connects, a new thread with a class is created. Here is the class:


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;
        }
    }
}

I am using netcat as a 'client' until I write my own. Is this perhaps why it causes the NPE? I have tried this all different kinds of outputstreams and writers and they all produce error at either the initialization, the write or the flush.

SamBkamp
  • 65
  • 8
  • 1
    Well if your initialization for `output` fails, you print out the stack trace and then keep going regardless - which would produce an NPE. I would strongly avoid you swallowing exceptions like that. Also, I strongly suspect that the problem is that your `output` initialization is in an initializer block which will be run *before* the body of the constructor. I'd recommend moving that code into the constructor. – Jon Skeet Sep 03 '19 at 13:52
  • @JonSkeet When I use a DataOutputStream, the initialization works fine and no NPE is thrown,it only gets thrown with a PrintWriter. Also, I didn't even notice that my output was in an initialization block, I moved it to the run function and now everything works. Im kicking myself... Thanks for the help man. – SamBkamp Sep 03 '19 at 14:03

1 Answers1

0

Thanks to the user John Skeet, I fixed the error. The problem was that I had the output DataOutputStream in an initialization block without realizing it. So to fix I had to just move that to the run() function and now everything works.

SamBkamp
  • 65
  • 8