package haolei.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
public class Server {
private static Server s = new Server();
private Socket st = null;
private ServerSocket ss = null;
private PrintWriter pw = null;
private BufferedReader br = null;
public static String ip = null;
public static int port;
@SuppressWarnings("static-access")
private Server() {
try {
ss = new ServerSocket(4545);
st = ss.accept();
ip = ss.getInetAddress().getLocalHost().getHostAddress();
port = 4545;
System.out.println(" new thread.");
new MyThread(st);
System.out.println("after thread.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static Server getInstance() {
return s;
}
public static void main(String[] args) {
Server.getInstance();
}
public String toString() {
return ip + ":" + port;
}
}
class MyThread extends Thread {
private static final int SHUTDOWN = 0;
private static final int REBOOT = 1;
private static final int LOGOUT = 2;
private static final int CANCEL = 3;
private PrintWriter pw = null;
private BufferedReader br = null;
private Socket st = null;
public MyThread() {
super();
}
public MyThread(Socket s) {
try {
st = s;
br = new BufferedReader(new InputStreamReader(st.getInputStream()));
pw = new PrintWriter(st.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
this.start();
}
public void run() {
try {
String line;
String type;
pw.println("ok");
pw.flush();
type = br.readLine();
line = br.readLine();
if (line.length() == 0) {
line = null;
}
while (!line.equals("bye")) {
if (!line.isEmpty() & type.equals("cmd")) {
int return_value = deal(line);
if (return_value != SHUTDOWN) {
break;
}
}
type = br.readLine();
line = br.readLine();
}
pw.close();
br.close();
st.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (st.isConnected()) {
pw.close();
}
}
}
private int deal(String line) {
int value = 0;
String cmd = null;
try {
value = Integer.parseInt(line);
switch (value) {
case SHUTDOWN:
cmd = "shutdown -s -t 0";
break;
case REBOOT:
cmd = "shutdown -r -t 0";
break;
case LOGOUT:
cmd = "shutdown -l";
break;
case CANCEL:
cmd = "shutdown -a";
break;
default:
value = -1;
}
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
}