关于hasnextLine()方法的一些理解
来源:互联网 发布:幸福蓝海网络学 编辑:程序博客网 时间:2024/05/20 17:58
以前对于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; }}
0 0
- 关于hasnextLine()方法的一些理解
- 关于线程方法的一些个人理解
- 关于hashcode()方法和equals()方法的一些理解
- 关于.net Enumerable的一些方法的理解
- 关于hashcode和equals方法重写的一些理解!
- 关于JAXB的一些理解
- 关于bitmap的一些理解
- 关于Hook的一些理解
- 关于JavaBean的一些理解
- 关于异常的一些理解
- 关于内存的一些理解
- 关于内存的一些理解
- 关于MFC的一些理解
- 关于编码的一些理解
- 关于枚举的一些理解
- 关于const的一些理解
- 关于矩阵的一些理解
- 关于编码的一些理解
- Java 1.5并发包之三:线程池实现之Fork/Join框架
- SDAU 练习三 1004 谦逊(卑微)数字
- 《Windows API》读取文件
- 恒生电子实习面筋
- 在eclipse中搭建struts2开发环境
- 关于hasnextLine()方法的一些理解
- QT5。怎么开启C++11标准
- 理解RESTful架构
- Java NIO系列教程(一) Java NIO 概述
- swift Reflection(字典转模型)变量继承本类类名解决办法
- 排列-hdu_1027_Ignatius and the Princess II
- Scala函数式编程原理 第二课 编程的本质(Elements of programing)
- opencv检测四边形/多边形
- 线程同步(7):linux和Windows线程池的实现-案例