Java TCP if语句
对于这个应用程序,用户发出一个命令,服务器返回一个回复。由于某种原因,Java TCP if语句,java,tcp,if-statement,Java,Tcp,If Statement,对于这个应用程序,用户发出一个命令,服务器返回一个回复。由于某种原因,if语句不工作,并且对于它运行的每个输入,sentance=“Unknown Command”+“\n”。我想知道我做错了什么 import java.io.*; import java.net.*; // SERVER class StartingPoint { public static void main(String argv[]) throws Exception{ double srv
if
语句不工作,并且对于它运行的每个输入,sentance=“Unknown Command”+“\n”代码>。我想知道我做错了什么
import java.io.*;
import java.net.*;
// SERVER
class StartingPoint {
public static void main(String argv[]) throws Exception{
double srvversion = 0.1;
double cliversion = 0.1;
String clientSentence;
String sentance = null;
String capitalizedSentence;
//Commands cmds = new Commands();
ServerSocket welcomeSocket = new ServerSocket(6789);
System.out.println("Server Started");
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase();
if(capitalizedSentence == "VERSION"){
sentance = "Current Server Version: " + srvversion
+ " | Current Client Version: " + cliversion + '\n';
}else{
sentance = "Unknown Command" + '\n';
}
outToClient.writeBytes(sentance);
System.out.println("Sent: " + sentance);
}
}
}
您应该使用.equals()方法来比较字符串,而不是使用==
改变
if(capitalizedSentence == "VERSION"){
到
要比较字符串,必须使用.equals()
方法,如下所示:
String str1;
String str2;
if (str1.equals(str2)) // do something
else //do something else
您可能应该打印出无效命令的内容--至少在尝试调试该命令时是这样的。。。。
String str1;
String str2;
if (str1.equals(str2)) // do something
else //do something else