以前对于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;
} }

最新文章

  1. 数论 - Moon Game
  2. MVC MODEL Attribute 操纵速记
  3. SQLite数据库在多线程写锁文件的解决办法
  4. GHOST(幽灵)重大漏洞
  5. Memcached和Redis对比和适用场景
  6. C#通过安全证书生成签名和验签辅助类
  7. 使用UIKit制作卡牌游戏(一)ios游戏篇
  8. DMSFrame 之简单用法(一)
  9. placeholder的字体样式改变,滚动条的颜色改变,ios日期兼容
  10. Xcode上传代码到github
  11. java实现多线程三种方法
  12. c# 图片加水印
  13. CF 552(div 3) E Two Teams 线段树,模拟链表
  14. vue自定义指令directives使用及生命周期
  15. 《温故而知新》JAVA基础五
  16. SSH登录启用Google二次身份验证
  17. 北京时间转为时间搓 标准时间转为UTC
  18. Nested Loops(嵌套循环)
  19. BZOJ.2882.工艺(后缀自动机 最小表示 map)
  20. AutoMapper在MVC中的运用05-映射中的忽略、处理null、多种映射转换

热门文章

  1. javascript动画:velocity.js学习
  2. HDU 2461 Rectangles#容斥原理
  3. POJ 2485 Highway(Prim+邻接矩阵)
  4. 2、Web应用程序中的安全向量 -- CSRF/XSRF(跨站请求伪造)
  5. linux 移除svn文件夹
  6. Java中需要总结的几个问题
  7. MFC HTTP
  8. redis数据类型:sets
  9. Linux下搭建ntp时间同步服务器
  10. A - LCM Challenge