Search code examples
javasocketsbufferedreader

After reading from socket can't write


I have client and server server site. Server is working good but client site when i'm trying to read is not.

But when I remove this code it works:

while((read = br.readLine()) != null){
    System.out.println("in reading");
    finale += read;
    output.setText(finale);
}           
br.close();

Here is the complete code:

try{
    Socket connection = new Socket("localhost",PORT);
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    pw.println("hi connection estabilished");
    pw.flush();
    String str,read = "",finale = "";
    while(connection.isConnected()){
        System.out.println("start");
        if(zapis == true){
            str = input.getText();
            pw.println(str);
            pw.flush();
            input.setText("");
            zapis = false;
        }
        System.out.println("top of the reading");
        while((read = br.readLine()) != null){
            System.out.println("in reading");
            finale += read;
            output.setText(finale);
        }           
        br.close();
    }
} catch(IOException e) { 
    System.out.println("error " + e); 
}

This is just class for listenning action of my button

class Listener implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
    Main.zapis = true;
}   
}

Solution

  • Apparently, you open br outside of the loop while(connection.isConnected()){ but you close it in the loop.

    You should try to write your last block (the one that make it works when you remove it) as :

        System.out.println("top of the reading");
        while((read = br.readLine()) != null){
            System.out.println("in reading");
            finale += read;
            output.setText(finale);
        }           
    }
    br.close();
    

    with the close outside of the loop.