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