您的位置:首页 > 其它

关于hasnextLine()方法的一些理解

2016-05-15 22:50 363 查看
以前对于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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: