62,614
社区成员
发帖
与我相关
我的任务
分享
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
try(Socket s=new Socket("127.0.0.1", 9080);) {
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
Scanner in=new Scanner(s.getInputStream());
out.write("i am client");
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
}
}
}
public class Server {
public static void main(String[] args) throws IOException {
try(ServerSocket ser = new ServerSocket(9080)){
try(Socket soc= ser.accept()){;
PrintWriter out=new PrintWriter(soc.getOutputStream(),true);
Scanner in = new Scanner(soc.getInputStream());
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
out.println("i am server");
}
}
}
}
public class Server {
public static void main(String[] args) throws IOException {
try(ServerSocket ser = new ServerSocket(9080)){
try(Socket soc= ser.accept()){;
Scanner in = new Scanner(soc.getInputStream());
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
in.close();
}
}
}
}
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
try(Socket s=new Socket("127.0.0.1", 9080);) {
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
Scanner in=new Scanner(s.getInputStream());
out.write("i am client");
out.flush();
out.close();
}
}
}
然后我调试,服务端执行到 while(in.hasNextLine()){ 这里阻塞了,客户端开始执行out.write("i am client");再执行flush,可是服务端依然阻塞,直到执行了close,服务端才走到下一行,这是怎么回事?难道flush没什么用?