Search code examples
javainstanceprintwriter

PrintWriter is null in java Server


I have got a problem setting up a server - client connection for a robot in java. I have got two clients listening to two different ports. When the server is sending an error is occurring the PrintWriter is null.

Perhaps the methods are in two different instances. But how can I fix that?

Server code:


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {

    // port for the TCP/IP network
    private static int port = 30001;
    public void setPort(int newPort) {
        port = newPort;
    }
    private ServerSocket serverSocket;
    private Socket socket;

    private PrintWriter pw;

    public void start() throws IOException {
        System.out.println("Server: Hi, I am ready to serve you!");
        System.out.println("Server: Trying to connect.");
    
        // get a connection
        try {
            serverSocket = new ServerSocket(port);
            socket = serverSocket.accept();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Server: I got a connection!");

        pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    public void sendString(String msg) {
        pw.println(msg);
        pw.flush(); 
    }

    public void stop() throws IOException {
        pw.close();
        socket.close();
        serverSocket.close();
        System.out.println("Server has stopped");
    }
}

Code of the coordinating class:

package ServerV4Test;

import java.io.IOException;

public class CoordinateServer {
    
    private Server myServer01 = new Server();
    private Server myServer02 = new Server();
    
    public void sendString(String msg) {
                    myServer01.sendString(msg);
                    myServer02.sendString(msg);
    }

    public void startServerMaster () throws IOException {
        System.out.println("The server coordinator started!");
        
                Server myServer01 = new Server();
                
                myServer01.setPort(30001);
                myServer01.start();
                
                Server myServer02 = new Server();

                myServer02.setPort(30002);
                myServer02.start();
    }
}

Programm code:


import java.io.IOException;

public class ProgramServer {
        
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        CoordinateServer coordServer = new CoordinateServer();
        coordServer.startServerMaster();


            String sendString = "hello world";
    
            coordServer.sendString(sendString);
            
            coordServer.closeServerMaster();
    }
}

Error message:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.PrintWriter.println(String)" because "this.pw" is null
    at ServerV4Test.Server.sendString(Server.java:40)
    at ServerV4Test.CoordinateServer.sendString(CoordinateServer.java:11)
    at ServerV4Test.ProgramServer.main(ProgramServer.java:16)

Client code:

import java.io.*;

import java.net.*;
import java.util.ArrayList;

public class Client {

    // set port and IP for the server
    private String hostname =  "localhost"; 
    private int port;
    public void setHostname (String sHost) {
        hostname = sHost;
    }
    public void setPort(int sPort) {
        port = sPort;
    }
    private InetSocketAddress address;
    private void createAddress() {
        address = new InetSocketAddress(hostname, port);
    }

    // create a list for the received strings
    private ArrayList<String> receivedList= new ArrayList<String>();

    public String getReceivedString() {
        String temp = receivedList.get(0); 
        receivedList.remove(0);
        return temp;
    }

    public boolean hasReceivedString() throws IOException {
        receiveString();
        if (receivedList.size() > 0) { 
            return true;
        }
        else {
            return false;
        }
    }

    private Socket socket;
    private BufferedReader bufReader;

    public void start() throws IOException {
        System.out.println("Client: I start myself!");
        System.out.println("Client: creating connection!");

        socket = new Socket();
        createAddress();

        socket.connect(address);

        System.out.println("Client: I got a connection!");

        InputStreamReader iStreamReader = new InputStreamReader(socket.getInputStream());
        bufReader = new BufferedReader(iStreamReader);
    }

    private void receiveString() throws IOException {
        while (bufReader.ready()) {
            if(bufReader.ready()) {
                String message = bufReader.readLine();
                receivedList.add(message);
            }
        }
    }

    public void stop() throws IOException {
        bufReader.close();
        socket.close();
        System.out.println("Client has stopped");
    }
}

Client programm:


import java.io.IOException;

public class ProgramUseClient1 {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("client testprogram started");

        // create an instance of the server
        Client myClient = new Client();

        myClient.setPort(30001);

        // start client
        myClient.start();

        // repeat receiving and sending
        boolean progRunning = true;
        while(progRunning) {

            // test if something is received
            if(myClient.hasReceivedString()) {
                String receivedString = myClient.getReceivedString();
                System.out.println("The client 1 received: " + receivedString);
                // test if client should be stopped
                myClient.stop();
                progRunning = false;
            }

        }
        System.out.println("Goodbye");
    }
}

Solution

  • You have created shadowed variables myServer01 and myServer02 where the global variables do not have PrintWriter pw initialized. Replace

    Server myServer01 = new Server();
    

    with

    myServer01 = new Server();
    

    and similarly for myServer02