关于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; } }
相关文章推荐
- Java基础--数据库连接方式
- 基于IntelliJ IDEA 15.0.2的Tomcat7.0.69源码运行环境搭建
- 如何学习一种开发框架
- 问题相关
- 开发转测试
- uva1343
- 代码混淆之坑点
- 产品思维学习(五)--产品敏捷开发和项目管理
- 厉害了!中国农历算法
- 131.Sum Root to Leaf Numbers
- Task执行内幕与结果处理解密
- Java虚拟机详解----JVM常见问题总结
- UML——对象图和类图
- 大型网站技术架构核心原理与案例分析
- 《java入门第一季》集合框架引入与面试题
- 线程同步(6):linux 多线程pthread中的各种函数
- maven学习系列7----将依赖依赖文件打包到jar中
- 《java入门第一季》集合框架引入与面试题
- 设计模式-1依赖倒置原则示例
- 百度之星2016资格赛 D