[置顶] 手机通过socket控制电脑关机,重启,注销等功能
服务端
package com.pc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.LineNumberReader;
public class Server extends Thread {
private ServerSocket server = null;
private static final int PORT = 20000;
private BufferedWriter writer;
private BufferedReader reader;
private Server() throws IOException {
CreateSocket();
// 创建Socket服务器
}
public void run() {
Socket client;
String txt;
try {
while (true)
// 线程无限循环,实时监听socket端口
{
client = ResponseSocket();
// 响应客户端链接请求。。
while (true) {
txt = ReceiveMsg(client);
// 链接获得客户端发来的命令
System.out.println(txt);
if (txt != null) {
// 执行命令
txt = exceCommand(txt);
}
SendMsg(client, txt);
// 向客户端返回消息
// 中断,关闭此次连接
break;
}
CloseSocket(client);
}
} catch (IOException e) {
System.out.println(e);
}
}
private void CreateSocket() throws IOException {
server = new ServerSocket(PORT);
System.out.println("Server starting..");
}
private Socket ResponseSocket() throws IOException {
Socket client = server.accept();
System.out.println("client connected..");
return client;
}
private void CloseSocket(Socket socket) throws IOException {
reader.close();
writer.close();
socket.close();
System.out.println("client closed..");
}
private void SendMsg(Socket socket, String Msg) throws IOException {
writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
writer.write(Msg + "\n");
writer.flush();
}
private String ReceiveMsg(Socket socket) throws IOException {
reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
System.out.println("server get input from client socket..");
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
return line;
}
return line;
}
private String exceCommand(String command) {
String msg = "";
try {
Process process = Runtime.getRuntime().exec(command);
InputStreamReader ir = new InputStreamReader(
process.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
msg += line + "\n";
}
} catch (java.io.IOException e) {
System.err.println("IOException " + e.getMessage());
}
return msg;
}
public static void main(final String args[]) throws IOException {
Server commandServer = new Server();
if (commandServer != null) {
commandServer.start();
}
}
}
客户端
package com.android.pc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button wifi1,baocun,guanji,chongqi,zhuxiao,quxiao,tuichu;
private EditText edit;
private Socket socket;
public static boolean wifi;
public static final int CONNENTED = 0;
public static final int UPDATALOG = 1;
// private TextView log;
private String ip="192.168.2.102";
private String logMsg;
private BufferedWriter writer;
private InetSocketAddress isa = null;
Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
findviews();
setonclick();
}
public void findviews() {
guanji=(Button)this.findViewById(R.id.guanji);
chongqi=(Button)this.findViewById(R.id.chongqi);
zhuxiao=(Button)this.findViewById(R.id.zhuxiao);
quxiao=(Button)this.findViewById(R.id.quxiao);
tuichu=(Button)this.findViewById(R.id.tuichu);
wifi1=(Button)this.findViewById(R.id.wifi);
edit=(EditText)this.findViewById(R.id.edit);
baocun=(Button)this.findViewById(R.id.baocun);
}
private void setonclick() {
guanji.setOnClickListener(new OnClickListener1());
chongqi.setOnClickListener(new OnClickListener2());
zhuxiao.setOnClickListener(new OnClickListener3());
quxiao.setOnClickListener(new OnClickListener4());
tuichu.setOnClickListener(new OnClickListener5());
wifi1.setOnClickListener(new OnClickListener6());
baocun.setOnClickListener(new OnClickListener7());
}
private class OnClickListener1 implements OnClickListener{
@Override
public void onClick(View v) {
String str1="shutdown -s";
tcpClient tcp = new tcpClient(str1.toString());
tcp.start();
}
}
class OnClickListener7 implements OnClickListener{
@Override
public void onClick(View v) {
ip=edit.getText().toString();
}
}
private class OnClickListener2 implements OnClickListener{
@Override
public void onClick(View v) {
String str2="shutdown -r";
tcpClient tcp = new tcpClient(str2.toString());
tcp.start();
}
}
private class OnClickListener3 implements OnClickListener{
@Override
public void onClick(View v) {
String str3="shutdown -l";
tcpClient tcp = new tcpClient(str3.toString());
tcp.start();
}
}
private class OnClickListener4 implements OnClickListener{
@Override
public void onClick(View v) {
String str3="shutdown -a";
tcpClient tcp = new tcpClient(str3.toString());
tcp.start();
}
}
private class OnClickListener5 implements OnClickListener{
@Override
public void onClick(View v) {
MainActivity.this.finish();
}
} private class OnClickListener6 implements OnClickListener{
@Override
public void onClick(View v) {
if(!wifi){
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("提示");
builder.setMessage("WIFI没有打开");
WifiManager w =(WifiManager)MainActivity. this.getSystemService(Service.WIFI_SERVICE);
w.setWifiEnabled(true);
Toast toast = Toast.makeText(MainActivity.this, "正在打开,请等待", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("PC ");
builder.setMessage("是否退出 ?");
builder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
return super.onKeyDown(keyCode, event);
}
public void connecttoserver() throws UnknownHostException, IOException {
socket = RequestSocket(ip, 20000);
if (socket.isConnected()) {
Message msg = new Message();
msg.what = CONNENTED;
mHandler.sendMessage(msg);
}
}
private Socket RequestSocket(String host, int port)
throws UnknownHostException, IOException {
Socket ConSocket = new Socket();
isa = new InetSocketAddress(host, port);
ConSocket.connect(isa);
return ConSocket;
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case CONNENTED:
break;
case UPDATALOG:
break;
}
}
};
private void SendMsg(Socket socket, String msg) throws IOException {
writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
Log.i("msg", msg.replace("\n", " ") + "\n");
writer.write(msg.replace("\n", " ") + "\n");
writer.flush();
}
private String ReceiveMsg(Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String line;
String txt = "";
while ((line = reader.readLine()) != null) {
txt += line + "\n";
}
reader.close();
return txt;
}
class tcpClient extends Thread {
String commandString;
public tcpClient(String command) {
commandString = command;
}
public void run() {
String recv;
try {
connecttoserver();
SendMsg(socket, commandString);
recv = ReceiveMsg(socket);
if (recv != null) {
logMsg += recv;
// close BufferedWriter and socket
writer.close();
socket.close();
// updata to log
Message msg = new Message();
msg.what = UPDATALOG;
mHandler.sendMessage(msg);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
activity_main.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/wifi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="连接无线"/>
<EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="输入IP"/>
<Button
android:id="@+id/baocun"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="连接到PC"/>
<Button
android:id="@+id/guanji"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="关机" />
<Button
android:id="@+id/chongqi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="重启" />
<Button
android:id="@+id/zhuxiao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="注销" />
<Button
android:id="@+id/quxiao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="取消关机" />
<Button
android:id="@+id/tuichu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="退出程序" />
</LinearLayout>