我使用Netbeans编写程序但是想在终端中运行以检查是否正在运行套接字编程。我能够成功编译第一个文件ServerClient.java但无法运行。这是我的编程文件
ServerProgram.java
package echoserver;
public class ServerProgram {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
ClientProgram.java
package echoserver;
public class ClientProgram {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java Client <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
){
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("socket: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
CMD:
Puja:echoserver pujadudhat$ javac ServerProgram.java
Puja:echoserver pujadudhat$ $javac ServerProgram.java -d
-bash: ServerProgram.java: command not found
Puja:echoserver pujadudhat$
答案 0 :(得分:0)
编译代码如下:
$javac YourJavaFileName.java -d .
在您的情况下:$javac ServerProgram.java -d .
。
然后按以下方式运行:
$java PackageName.ClassName
在您的情况下:java echoserver.ServerProgram
。
您可以引用其他类似的question here。