Bufferedreader always returns null

Asked

Viewed 143 times

1

Although some questions already exist with similar subject matter, I could not get an exact answer, so I turn again to Stack.

I’m developing a client-server system, I already had the project earlier, and I decided to start from scratch:

CLIENT

I had to delete some lines of code to find out where the error was. The error is found when using the in.read() or in.readLine(), always returns an exception.

private Socket socket = null;
private int port = 2048;
private String host;
private Utilizador utilizador;
private Mensagem mensagemServidor;
private static PrintWriter out = null;
private static BufferedReader in = null;
//  private static ObjectOutputStream objectOut;
//private static ObjectInputStream objectIn;
private static int vefVariable;
private static String mensagemServidorThr;

/**
 * Construtor para ser usado na conecção ao servidor pela primeira vez pelo
 * utilizador
 *
 * @param hostInstace
 * @param user
 */
public Socket_Client(String hostInstace, Utilizador user) {
    this.host = hostInstace;
    this.utilizador = user;
}

/**
 * Construtor para ser usado para envio de mensagem do cliente para o
 * servidor
 *
 * @param user utilizador que envia a mensagem
 * @param mensagem mensagem que o utilizador mandou.
 */
public Socket_Client(Mensagem mensagem) {
    this.mensagemServidor = mensagem;
}

public void connecttoServer() throws IOException {

    try {
        socket = new Socket(host, port);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    } catch (UnknownHostException e) {
        System.err.println("Não existe informação com o servidor" + host);

    } catch (IOException e) {
        System.err.println("Não existe informação com o servidor" + host);

    }
    out.println("tudobem");
    System.out.println(in.read());
}

SERVER

public static void main(String[] args) throws IOException {

    ServerSocket srvSckt = null;
    int porto = 2048;
    boolean listening = true;

    //conecao ao servidor
    try {
        srvSckt = new ServerSocket(porto);
        System.out.println("Conecção ao Servidor efectuada com sucesso!");
    }catch(IOException ex) {
        System.err.println("Impossível coneção a porta \t" +porto);
    }
    Socket clientSocket = null;

    clientSocket = srvSckt.accept();
}

I think the communication with the part of the server is missing, but I have tried and still does not work, this time I do not see the elements of the graphical interface.

1 answer

1


The server accepts the connection but soon after the program is terminated, so the connection will be closed.

The method readLine returns null (read returns -1) because the connection was closed soon after opening.

Here the excerpt of the code in question (with problem) commented:

public static void main(String[] args) throws IOException {

    ...

    clientSocket = srvSckt.accept();  // aceita a conexão
}                                     // main, programa, conexão terminam/fecham

in other words, it is missing the code that will deal with customer communication. At least you have to make a reading of the clientSocket to read the sentence sent by the customer and then send the reply to the customer. Usually this occurs in a loop until the connection is closed, depending on the protocol used (for example: client sends "Exit" to end the connection).

Example (very simplified):

public static void main(String[] args) throws IOException {

    ...

    clientSocket = srvSckt.accept();

    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

    String str = in.readLine();
    System.out.printf("Servidor recebeu \"%s\"\n", str);
    out.write('X');
    out.flush();

    // outros comandos, se terminar o main provavelmente o cliente
    // não irá receber a respota
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    clientSocket.close();
}

Browser other questions tagged

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