即使存在 .class 文件,也没有 class 错误

No class error even though the .class files are present

获取 Error: Could not find or load main class KnockKnockServer,当 运行 以下代码使用 java KnockKnockServer 4444 时,即使 class 文件 KnockKnockServer.class 存在于目录中。

我正在关注 this link 以了解服务器-客户端的工作方式。

 import java.net.*;
 import java.io.*;

public class KnockKnockServer {
public static void main(String[] args) throws IOException {

    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
        System.err.println("Could not listen on port: 4444.");
        System.exit(1);
    }

    Socket clientSocket = null;
    try {
        clientSocket = serverSocket.accept();
    } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
    }

    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
            clientSocket.getInputStream()));
    String inputLine, outputLine;
    KnockKnockProtocol kkp = new KnockKnockProtocol();

    outputLine = kkp.processInput(null);
    out.println(outputLine);

    while ((inputLine = in.readLine()) != null) {
         outputLine = kkp.processInput(inputLine);
         out.println(outputLine);
         if (outputLine.equals("Bye."))
            break;
    }
    out.close();
    in.close();
    clientSocket.close();
    serverSocket.close();
}
}

如果您不在命令行上传递类路径,它会考虑 CLASSPATH 环境变量。并且只有当那个也没有设置时,它才会考虑默认值,即“.”

因此,要么取消设置 CLASSPATH 环境变量,要么在命令行中传递 -cp .