Nullpointerexception when connecting the server

Asked

Viewed 48 times

2

I am making a program in Java server/client. When I start the server class I see the error

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

I leave the code below so you can 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);
    }

}

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

Please help me out!

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.