我有这个 tcp/ip 程序,如果用户输入“再见”。它将停止连接并结束程序。然而,当我输入“再见”时。从客户端来看,它不会执行 if 语句,而是执行其他语句。
程序的一部分
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
out.println(inputLine);
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
if (inputLine.equals("Bye.")) {
System.out.println("Exit program");
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
程序的较大部分
public static void server(Scanner input1, Scanner input2, Scanner input3, Scanner input4) throws IOException{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(57634);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
out.println(inputLine);
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
if (inputLine.equals("Bye.")) {
System.out.println("Exit program");
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
最佳答案
从您的代码中,如果用户输入“再见”。它会打破 while 循环,但永远不会关闭输入/输出流,也不会关闭客户端/服务器套接字。
out.close();
in.close();
clientSocket.close();
serverSocket.close();
上面的代码发生在 if
语句之后的 while
循环中。但是,如果您的 if
语句为 true,则循环将中断并且不会到达这些语句。
关于java - 为什么我的程序跳过 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17796990/