Java Socket远程关机,重启
摘要
-通过Java Socket实现远程关机,重启命令
-以下,直接贴代码,代码实现了服务端操作,客户端响应关机,重启操作
客户端(执行远程命令)
package test.shutdown;
/**
* Created by zqq3436 on 2017/3/14.
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client implements Runnable {
String s = null;
Socket mysocket;
DataInputStream in = null;
DataOutputStream out = null;
Thread thread = null;
public Client() {
//初始化socket,并开启发送命令的线程
thread = new Thread(this);
try {
//线程休眠
Thread.sleep(500);
mysocket = new Socket("localhost", 9090);//localhost可修改为连接服务端的IP地址
//下面是初始化流
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
//开启发送命令的线程
thread.start();
}
//入口方法
public static void main(String args[]) {
new Client();
}
//执行命令的方法
public void ExeCmd(String s) {
try {
Runtime ec = Runtime.getRuntime();
ec.exec(s);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
//读取远程命令
String s = in.readUTF();
ExeCmd(s);//调用方法运行远程命令
Thread.sleep(200);
} catch (Exception e) {
}
try {
//每执行一个命令,需要休眠
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
服务端(发送远程命令)
“`
package test.shutdown;
/**
* Created by zqq3436 on 2017/3/14.
*/
import java.net.*;
import java.io.*;
public class Server {
ServerSocket server=null;
Socket you=null;
String s=null;
DataOutputStream out=null;
public Server(){
//初始化ServerSocket
try{
server=new ServerSocket(9090);
System.out.println(“wait…..”);
you=server.accept();
//初始化输出流
out=new DataOutputStream(you.getOutputStream());
}catch(Exception e){
}
}
//入口方法,开启远程发送命令线程
public static void main(String args[])
{
Server server=new Server();
//打开对方的控制台
server.sendOrder("mmc");
//每发送一个命令,需要休眠
try{Thread.sleep(500);}catch(Exception e){}
server.sendOrder("shutdown -s -t 5");// 让对方在5秒内关机,"shutdown -r -t 5"表示5秒内重启
//每发送一个命令,需要休眠
try{Thread.sleep(500);}catch(Exception e){}
server.sendOrder("shutdown -a");//取消关机
}
//发送命令的方法
public void sendOrder( String s)
{
try{
out.writeUTF(s);
}catch(Exception e){
}
}
}
尾注
-此处,也可以更改为使客户端发送命令,服务器端执行远程命令,代码极为相似,这里不再举出