客户端
1 import java.io.*; 2 import java.net.*; 3 4 public class DailyAdviceClient { 5 public void go() { 6 try { 7 Socket s = new Socket("127.0.0.1", 4242); 8 InputStreamReader streamReader = new InputStreamReader( s.getInputStream() ); 9 BufferedReader reader = new BufferedReader( streamReader ); 10 11 String advice = reader.readLine(); 12 System.out.println("Today you should: " + advice); 13 reader.close(); 14 } catch (IOException ex) { 15 ex.printStackTrace(); 16 } 17 } 18 19 public static void main(String[] args) { 20 DailyAdviceClient client = new DailyAdviceClient(); 21 client.go(); 22 } 23 }
服务器端:
1 import java.io.*; 2 import java.net.*; 3 4 public class DailyAdviceServer { 5 6 String[] adviceList = { 7 "Take smaller bites", 8 "Go for the tight jeans. No they do NOT make you lookk fat.", 9 "One word: inappropriate", 10 "Just for today, be honest. Tell your boss what you *really* think", 11 "You might want to rethink that harcut." 12 }; 13 14 public void go() { 15 try { 16 ServerSocket serverSock = new ServerSocket(4242); 17 while (true) { 18 Socket sock = serverSock.accept(); 19 PrintWriter writer = new PrintWriter(sock.getOutputStream()); 20 String advice = getAdvice(); 21 writer.println(advice); 22 writer.close(); 23 System.out.println(advice); 24 } 25 } catch (IOException ex) { 26 ex.printStackTrace(); 27 } 28 } 29 30 private String getAdvice() { 31 int random = (int) (Math.random() * adviceList.length); 32 return adviceList[random]; 33 } 34 35 public static void main(String[] args) { 36 DailyAdviceServer server = new DailyAdviceServer(); 37 server.go(); 38 } 39 }
先运行服务器端,然后运行客户端。
我很好奇客户端的读取操作会等待吗?
String advice = reader.readLine();
如果客户端在执行到这条语句的时候服务器端还没有发消息怎么办?客户端直接返回空还是会等待?等待多久?
因此先做了如下实验:
实验1:把服务器端的发送语句去掉:
//writer.println(advice);
实验结果:客户端读到空串后马上结束
实验2:在服务器端发消息的时候增加一个延迟:
String advice = getAdvice();
try {
Thread.sleep(60000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
writer.println(advice);
实验结果:客户端会等待这个延迟后读取完整的消息。
这就有个疑问:客户端是怎么知道服务器端有消息要发送而去等待?猜想和服务器端的这条语句有关:
writer.close();
只要服务器端不关闭这个writer,而且客户端没有读到任何消息,则会一直等待,直到读到消息为止。
实验3:把服务器端的关闭writer的语句去掉
//writer.close();
实验结果:客户端会一直等待消息不会结束。
实验4:在服务器端连续发两条消息:
writer.println("Hi");
writer.println(advice);
实验结果:客户端只收到第一条后就结束。