gpt4 book ai didi

Java TCP if 语句

转载 作者:可可西里 更新时间:2023-11-01 02:47:31 26 4
gpt4 key购买 nike

对于此应用程序,用户发出命令,服务器发回回复。 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"){

  if(capitalizedSentence.equals("VERSION")){

关于Java TCP if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8664373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com