我有一个简单的服务器:
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(2004); //Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 2004");
}
System.out.println("Server started. Listening to the port 2004");
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
// getCommand(message);
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
private void getCommand(String message) throws IOException{
switch (message) {
case "1":
turnOffComputer();
break;
default:
break;
}
}
private void turnOffComputer() throws IOException{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 0");
System.exit(0);
}
}
现在我想添加功能,如果我在消息中获得数字 1,我想使用方法 getCommand() 来关闭计算机。我应该如何更改我的代码来做到这一点?
编辑:这是我的客户:
try {
client = new Socket(IP_ADDRESS, PORT); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});