Search code examples
javaclient-serverserver-sidebufferedreader

BufferedReader, Client/Server


For class I am creating a simple client/server. The client opens a jframe, where the user enters the host and port number. If a connection is made, another jframe is opened that has a keylistener. What is typed on the client's side is displayed in the server's jtextarea. I am able to make the connection between client and server, but after this I run into null pointer exception right after. I assume I should be using something else than bufferedreader in my server, or if I could stop the server from reading in until something is actually entered? Or am I doing something else completely wrong? Any help would be appreciated, and the relevant code is below.

public class TypeServer extends JPanel {

BufferedReader lnr;


public TypeServer(Socket soc) throws IOException {

    InputStream inStream = soc.getInputStream();
    InputStreamReader isr = new InputStreamReader(inStream);
    BufferedReader lnr = new BufferedReader(isr);


}
//below is in the main function
try {
        ServerSocket srv = new ServerSocket(5555);
        Socket soc=srv.accept();
        while (true) {


            // Create server
            TypeServer tc = new TypeServer(soc);
            String line=tc.lnr.readLine();
            textArea.append(line);
            srv.close();
            soc.close();

        }
    }

EDIT: I apologize for not including this before, but the String line=tc.lnr.readLine(); line hits the null pointer exception


Solution

  • In your main you are using the instance variable

    String line=tc.lnr.readLine(); //lnr is not initialized
    

    You have to change the following

    BufferedReader lnr = new BufferedReader(isr); //initializing the local variable
    

    to

    this.lnr = new BufferedReader(isr);