NullPointerException when connecting to server

2

I'm doing a server / client Java program. When I start the server class I get the error

  

Exception in thread "Thread-0" java.lang.NullPointerException

I'll leave the code below to help me solve the problem:

public class Servidor implements Runnable {

    HashMap<String, ServerOutput> utilizadorLigados;
    private ArrayList<Mensagem> listaMensagensEntregar = new ArrayList<Mensagem>();
    ServerSocket server = null;
    private int port;
    private Thread serverthread;


    public Servidor(int port) {

        this.port = port;
        utilizadorLigados = new HashMap<String, ServerOutput>();
    }

    @Override
    public void run() {

        synchronized (this) {
            this.serverthread = Thread.currentThread();

        while (true) {

        Socket cliente = null;
            try {
                System.out.println("1");
                cliente = this.server.accept();
                System.out.println("2");
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Erro ao aceitar o cliente", e);
            }

            new Thread(new ServerInput(this, cliente)).start();
            System.out.println("Servidor ligado");
            }
        }
    }

    public void abrirPortasServidor() {
        try {
            this.server = new ServerSocket(port);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

    }

    public HashMap<String, ServerOutput> getUtilizadorLigados() {
        return utilizadorLigados;
    }

    public ServerOutput getServerOutput(String clinte) {

        return utilizadorLigados.get(clinte);
    }

}

In the console, the program does sysout "1" of run, but does not do "2" so the problem is in line cliente = this.server.accept();

Please help me!

    
asked by anonymous 14.12.2015 / 14:08

1 answer

1

You must create an instance of ServerSocket , you are declaring it as a null object

try:

  @Override
public void run() {

    synchronized (this) {
        this.serverthread = Thread.currentThread();

        //Inicializa o server
        this.server = new ServerSocket();

    while (true) {

    Socket cliente = null;
        try {
            System.out.println("1");
            cliente = this.server.accept();
            System.out.println("2");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Erro ao aceitar o cliente", e);
        }

        new Thread(new ServerInput(this, cliente)).start();
        System.out.println("Servidor ligado");
        }
    }
}
    
14.12.2015 / 14:21