Java TCP if 语句
对于此应用程序,命令来自用户,服务器发回回复。 if
语句由于某种原因不起作用,对于每个输入,它都会运行 sentence = "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);
}
}
}
For this application a command comes in from the user and the server sends back a reply. The if
statement is not working for some reason and for every input it runs sentance = "Unknown Command" + '\n';
. I was wondering what I'm doing wrong.
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 .equals() 方法来比较字符串,而不是使用 ==。
更改
为
You should use .equals() method for comparing strings instead of using ==.
Change
to
要比较字符串,您必须使用
.equals()
方法,如下所示:To compare strings, you have to use
.equals()
method as following: