BufferedReader always returns null

1

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

I'm developing a client-server system, I already had the most advanced project, and I decided to start from the beginning:

CLIENT

I had to delete some lines of code to figure out where the error was. The error is when I use in.read() or in.readLine() , it always ends by returning 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 server part is missing, but I have tried and it still does not work, this time the elements of the graphical interface do not appear to me.

    
asked by anonymous 08.12.2017 / 00:38

1 answer

1

The server accepts the connection, but then 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 it was opened.

Here is 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, the code that will deal with communication with the client is missing. At least you have to read clientSocket to read the phrase sent by the client and then send the response to the client. Usually this occurs in a loop until the connection is closed, depending on the protocol used (for example: client sends "exit" to terminate 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();
}
    
08.12.2017 / 15:08