从socket读取后无法写入

时间:2014-06-20 16:11:44

标签: java sockets bufferedreader

我有客户端和服务器服务器站点。服务器工作正常,但我尝试阅读的客户端网站不是。

但当我删除此代码时,它可以工作:

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

以下是完整的代码:

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

这只是我按钮的聆听动作的课程

class Listener implements ActionListener{

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

1 个答案:

答案 0 :(得分:0)

显然,您在循环br之外打开while(connection.isConnected()){,但在循环中将其关闭。

您应该尝试编写最后一个块(在删除它时使其工作的块):

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

关闭外部