服务端

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>

[置顶] 手机通过socket控制电脑关机,重启,注销等功能的更多相关文章

  1. C# 操作电脑 关机 重启 注销 休止 休眠

    // 关机 强制电脑10秒之内关机 //System.Diagnostics.Process.Start("shutdown", "-s -f -t 10"); ...

  2. C# 关机/重启/注销计算机

    一.调用 shutdown.exe 执行操作 调用 shutdown.exe 执行计算机关机.重启.注销操作,还可以设置多长时间后执行操作,代码如下: 1 /// <summary> 2 ...

  3. Linux关机重启注销(3)

    1.关机重启 shutdown shutdown -h now :立即关机 shutdown -h 1 now :一分钟后关机 shutdown -r now :立即重启 halt:关机 reboot ...

  4. linux基础_关机重启注销

    1.关机重启命令 (1)shutdown shutdown -h now:表示立即关机 shutdown -h 1:表示1分钟后关机 shutdown -r  now:立即重启 (2)halt:就是直 ...

  5. Runtime单例模式类 -- 控制电脑关机

    package demo1; import java.io.IOException; public class RunTimeDemo { public static void main(String ...

  6. PHPCMS实现文章置顶功能的方法

    我个人喜欢把PHPCMS当作博客来用,而作为一个博客,怎能少了文章置顶功能呢?其中用PHPCMS实现置顶功能非常简单,无非是修改下推荐位的名称为置顶,然后在文章列表中推送需要置顶的文章罢了. 不过博客 ...

  7. 手机控制电脑定时关机,重启WiFi

    需求 晚上上床,电脑开着WiFi让手机上网.要么上床之前就给电脑设置定时关机:要么就电脑开通宵:要么就待会下来关电脑.这3种情况都非常不好,要么麻烦,要么浪费. 最无奈的是电脑刚开好WiFi,上床后才 ...

  8. 手机控制电脑,在WIFI局域网下(关机,重启,遥控)

    这个软件叫百变遥控:http://blog.sina.com.cn/s/blog_9abc7dbc0101hmut.html 今天周末,在家里看电影,家里用的是台式电脑,我自己买了一个投影仪来专门看视 ...

  9. Andy - 又一款速度流畅的免费安卓 Android 模拟器 (支持手机无线控制电脑模拟器)

    随着 Genymotion.BlueStacks 等电脑上的 Android 模拟器流行起来之后,似乎很多人都发现在电脑上运行使用安卓APP软件.畅玩手机游戏确实很有乐趣. 今天我们又发现了一款全新免 ...

随机推荐

  1. linux下gcc编译的参数详细说明

    参考网址:1 http://hi.baidu.com/zengzhaonong/item/f1f9383565fa5c302e0f8125 gcc使用方法 汇总 2 http://s99f.blog. ...

  2. 从零开始学ios开发(十九):Application Settings and User Defaults(上)

    在iphone和ipad中,有一个东西大家一定很熟悉,那个东西就是Settings. 这次要学习的东西说白了很简单,就是学习如何在Settings中对一个app的某些属性进行设置,反过来,在app中更 ...

  3. How to: Add SharePoint 2010 Search Web Parts to Web Part Gallery for Upgraded Site Collections

    When you upgrade to Microsoft SharePoint Server 2010, some of the new SharePoint Enterprise Search W ...

  4. [转载]C# FTP操作工具类

    本文转载自<C# Ftp操作工具类>,仅对原文格式进行了整理. 介绍了几种FTP操作的函数,供后期编程时查阅. 参考一: using System; using System.Collec ...

  5. [转载]点评阿里云、盛大云等国内IaaS产业

    免责声明:     本文转自网络文章,转载此文章仅为个人收藏,分享知识,如有侵权,请联系博主进行删除.     原文作者:刘黎明      原文地址:http://www.chinacloud.org ...

  6. CSS滤镜详解

    语法:STYLE="filter:filtername(fparameter1, fparameter2...)" (Filtername为滤镜的名称,fparameter1.fp ...

  7. [转载]数据库存储图片(MSSQL/ORACLE/ACCESS

    下面我来汇总一下如何将图片保存到SqlServer.Oracle.Access数据库中.首先,我们要明白图片是以二进制的形式保存在数据库中的,那么把图片保存到数据库中的步骤大体上有这几步1.将图片转换 ...

  8. 【Asp.net MVC ---杂七杂八】

    @RenderSection 母模板:_mainLayout.cshtml <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitio ...

  9. NGINX的奇淫技巧 —— 3. 不同域名输出不同伺服器标识

    NGINX的奇淫技巧 —— 3. 不同域名输出不同伺服器标识 ARGUS 1月13日 发布 推荐 0 推荐 收藏 6 收藏,707 浏览 大家或许会有这种奇葩的需求...要是同一台主机上, 需要针对不 ...

  10. 深入理解Tornado——一个异步web服务器

    本人的第一次翻译,转载请注明出处:http://www.cnblogs.com/yiwenshengmei/archive/2011/06/08/understanding_tornado.html原 ...