在socket编程的时候,用到了java.io.PrintWriter这个类。对这个类的flush功能尝试了下。
PrintWriter类的两种形式的构造函数如下:
如果设置autoFlush为true,那么后续在执行PrintWriter的 println, printf, 或者format函数的时候,会自动flush,不需要调用 PrintWriter的flush。反之,如果设置autoFlush为false,那么后续在执行PrintWriter的 println, printf, 或者format函数之后,还需要调用 PrintWriter的flush。
代码示例,下面两段代码实现的功能是一样的。借用了《Java高手真经__编程基础卷:Java核心编程技术》的代码来修改对比说明。
代码片段1:在构造PrintWriter的时候,设置autoFlush为true,在调用println之后,不需要再调用PrintWriter的flush:
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriter os = new PrintWriter(socket.getOutputStream());
PrintWriter os = new PrintWriter(socket.getOutputStream(), true);
// 循环处理客户端输入
String line;
while ((line = is.readLine()) != null) {
System.out.println("收到:" + line);
if (line.equals("bye")) {
break;
} else {
// 回复客户端
os.println(line);
//os.flush();
}
}
代码片段2:在构造PrintWriter的时候,不设置autoFlush的值(就没有自动flush功能),在调用println之后,再调用PrintWriter的flush:
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
//PrintWriter os = new PrintWriter(socket.getOutputStream(), true);
// 循环处理客户端输入
String line;
while ((line = is.readLine()) != null) {
System.out.println("收到:" + line);
if (line.equals("bye")) {
break;
} else {
// 回复客户端
os.println(line);
os.flush();
}
}