-
-
[原创]实现android控制PC
-
发表于:
2015-6-8 11:51
13738
-
首先建立服务端:利用socket通信持续监听客户端发来的消息再做相应的操作
public class Pc_service {
static ServerSocket serversocket = null;// 服务socket
static DataInputStream data_input = null;// 输入流
static DataOutputStream data_output = null;// 输出流
public static void main(String[] args) {
try {
//开启WiFi
startNet();
// 监听30000端口
serversocket = new ServerSocket(30000);
System.out.println("listening 30000 port");
while (true) {
// 获取客户端套接字
Socket client_socket = serversocket.accept();
String send_msg = "";
try {
// 获取输入流,读取客户端传来的数据
data_input = new DataInputStream(client_socket
.getInputStream());
String msg = data_input.readUTF();
System.out.println(msg);
// 判断输入,进行相应的操作
data_output = new DataOutputStream(client_socket
.getOutputStream());
if ("shutdown".equals(msg)) {
Shutdown();
// 发送消息回Android端
send_msg = "60秒后关机 ";
} else if ("restart".equals(msg)) {
Restart();
send_msg = "60秒后重启";
} else if ("cancel".equals(msg)) {
cancel();
send_msg = "关机已取消";
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
if (data_output != null) {
data_output.writeUTF(send_msg);
data_output.close();
}
data_input.close();
// 关闭连接
client_socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//打开承载网络
private static void startNet()throws IOException{
Process p = Runtime.getRuntime().exec("netsh wlan start hostednetwork");
}
// 关机
private static void Shutdown() throws IOException {
Process p = Runtime.getRuntime().exec("shutdown -s -t 60");
System.out.println("shutdown ,60 seconds later ");
}
// 重启
private static void Restart() throws IOException {
Process p = Runtime.getRuntime().exec("shutdown -r -t 60");
System.out.println("restart ,60 seconds later ");
}
// 取消登陆
private static void cancel() throws IOException {
Process p = Runtime.getRuntime().exec("shutdown -a");
System.out.println("cancel ");
}
}
Socket socket = new Socket();
InetSocketAddress s = new InetSocketAddress(resultIP+i, 30000);
socket.connect(s,50);
for(int i=1;i<255;i++){
try {
Socket socket = new Socket();
InetSocketAddress s = new InetSocketAddress(resultIP+i, 30000);
socket.connect(s,50);
Message message = new Message();
message.what=1000;
message.obj=resultIP+i;
handler.sendMessage(message);
flag =true;
socket.close();
break;
} catch (IOException e) {
handler.sendEmptyMessage(i);
}
}
[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!