有这样一个例子:
public class EchoServer
{
public static void main(String[] args)
{
try
{
ServerSocket s = new ServerSocket(8189);
Socket incoming = s.accept();
try
{
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream, true);
out.println("hello! enter BYE to exit."); boolean done = false; while(!done && in.hasNextLine())
{
String line = in.nextLine();
out.println("Echo:" + line);
if(line.trim().equals("BYE"))
done = true;
}
}
finally
{ incoming.close();}
}
catch(IOException e)
{
} }
}
程序运行后,用telnet 127.0.0.1 8189连接服务器,然后输入
Hello Server
服务器返回
Echo:Hello Server然后再输入BYE
服务器返回
Echo:BYE有个问题是:循环的条件是 while(!done && in.hasNextLine())
当第一次输入Hello Server之后,in.hasNextLine()应该为false了啊?为什么没有退出循环呢?
public class EchoServer
{
public static void main(String[] args)
{
try
{
ServerSocket s = new ServerSocket(8189);
Socket incoming = s.accept();
try
{
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream, true);
out.println("hello! enter BYE to exit."); boolean done = false; while(!done && in.hasNextLine())
{
String line = in.nextLine();
out.println("Echo:" + line);
if(line.trim().equals("BYE"))
done = true;
}
}
finally
{ incoming.close();}
}
catch(IOException e)
{
} }
}
程序运行后,用telnet 127.0.0.1 8189连接服务器,然后输入
Hello Server
服务器返回
Echo:Hello Server然后再输入BYE
服务器返回
Echo:BYE有个问题是:循环的条件是 while(!done && in.hasNextLine())
当第一次输入Hello Server之后,in.hasNextLine()应该为false了啊?为什么没有退出循环呢?
仔细看看&&,同时成立
!!!!done否操作
第一次循环开始前,done=false(初始化)
打印 Hello Server后,因为不是“BYE”,所以done还是 false
现在结果就是 while(!false && X ) 成立了 也就是说,X=true第二次退出,是因为 line.trim().equals("BYE")=true,所以done=true,所以while(!true && X ) 不成立了所以,第一次没退出的原因,就是 in.hasNextLine()=true, 可以加个打印试试。
至于为啥是true,就要看看代码了。
hasNextLine()方法描述如下:如果在此扫描器的输入中存在另一行,则返回 true。在等待输入信息时,此方法可能阻塞。扫描器不执行任何输入。也就是说在第一次你输入完Hello Server之后,程序会阻塞在那边,等待用户的继续输入,程序才会继续往下跑。