以前對於hasnextline的理解就是 :判斷是否有下一個值
今天發現了個特例,它竟然是個阻塞式的方法
看下面一個案例
這是服務器
package Service; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Service_1 { public static void main(String [] args) throws IOException{ ServerSocket ss=new ServerSocket(9999); System.out.println("我是服務器"+ss.getInetAddress()); Scanner sc=null; PrintWriter pw=null; int i=1; while(true){ Socket s=ss.accept(); System.out.println("有一個端口連接上來"+s.getInetAddress()); //獲取輸入流 sc=new Scanner(s.getInputStream()); pw=new PrintWriter(s.getOutputStream()); // pw.println("I am Server "+i); // pw.flush(); //System.out.println(sc.hasNextLine()); //如果這里加了這一行會形成阻塞的 do{ pw.println("I am Server "+i); pw.flush(); if(sc.hasNextLine()){ System.out.println("這個客戶端對我說:"+sc.nextLine()); } i++; }while(true); } } }
客戶端
import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class TestClient4 { /** * @param args * @throws IOException * @throws */ public static void main(String[] args) throws IOException { Socket s=new Socket("localhost",9999); System.out.println("客戶端連接上"+s.getLocalPort()); Scanner sc=new Scanner(s.getInputStream()); PrintWriter pw=new PrintWriter(s.getOutputStream()); //先接 while( sc.hasNextLine()){ String line=sc.nextLine(); line=new String(line.getBytes(),"UTF-8"); System.out.println("服務器"+s.getInetAddress()+"客戶端說"+line); if( "bye".equals(line)){ System.out.println("服務器"+s.getInetAddress()+"斷開了與客戶端的連接"); s.close(); break; } //回復服務器 String response=talk( s.getInetAddress().toString()); pw.println(response); pw.flush(); if( "bye".equals(response)){ System.out.println("客戶端主動斷開與服務器的連接"); s.close(); break; } } } public static String talk(String client){ Scanner sc =new Scanner(System.in); System.out.println("客戶端表達的話:"); String line=sc.nextLine(); return line; } }