I have a simple server:
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);
}
}
now I want to add functionality that if I get number 1 in message I want to use method getCommand() to turn off the computer. How should I change my code to do that?
EDIT: this is my client:
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();
}
}
});