PC 端通过 USB 与 android 端通信

 PC 端通过 USB 与 android 端通信

 整体思路 与 网上给出的 通过 socket 通信一致  重写代码终于调通

目录

 PC 端通过 USB 与 android 端通信


 

 

C# 代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form 
    {
        //声明变量
        string preimei, imei;
        String cmd = Application.StartupPath + "\\adb.exe";
        Process p = new Process();
        int TSleep = 3000;
        //
        
        public Form1()
        {
            InitializeComponent();
        }
        private string executeAdb(string adb)
        {
            p.StartInfo = new System.Diagnostics.ProcessStartInfo();
            p.StartInfo.FileName = cmd;//设定程序名 
            p.StartInfo.Arguments = adb;
            p.StartInfo.UseShellExecute = false; //关闭shell的使用 
            p.StartInfo.RedirectStandardInput = true; //重定向标准输入 
            p.StartInfo.RedirectStandardOutput = true; //重定向标准输出 
            p.StartInfo.RedirectStandardError = true; //重定向错误输出 
            p.StartInfo.CreateNoWindow = true;//设置不显示窗口 
            p.Start();
            String restr = "";
            restr = p.StandardOutput.ReadToEnd();
            p.Close();
            return restr;

        }
        //结束同步
        private void button2_Click(object sender, EventArgs e)
        {
            String exAdb = " shell am broadcast -a NotifyServiceStop";
            executeAdb(exAdb);

        }
        private static byte[] result = new byte[1024];
        Socket clientSocket = null;
        static IPAddress ip = IPAddress.Parse("127.0.0.1");
        //发送数据
        private void button3_Click(object sender, EventArgs e)
        {
            //通过 clientSocket 发送数据  
            try
            {
               
                string sendMessage = textBox1.Text;
                clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));
                Console.WriteLine("向服务器发送消息:{0}" + sendMessage);

                int receiveLength = clientSocket.Receive(result);
                String andStr = Encoding.UTF8.GetString(result, 0, receiveLength);
                Console.WriteLine("接收服务器消息:{0}", andStr);
                label4.Text = andStr;
            }
            catch
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();

            }
            Console.WriteLine("发送完毕,按回车键退出");
            Console.ReadLine();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //获取手机型号
            String phonModel =" shell getprop ro.product.model";
            label2.Text = executeAdb(phonModel);

            //String exAdb = "  devices";
            String adb_rstr = "";
            String exAdb = null;
            //端口
            exAdb = " forward tcp:12580 tcp:10086";
            adb_rstr = executeAdb(exAdb);
            //转换结果
            exAdb = " forward --list";
            adb_rstr = executeAdb(exAdb);
            //发送开启手机服务监听广播
            exAdb = " shell am broadcast -a NotifyServiceStart";
            adb_rstr = executeAdb(exAdb);
      
            //作为客户端链接
          
            if (clientSocket == null)
            {
             clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 12580)); //配置服务器IP与端口  
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                Console.WriteLine("连接服务器失败,请按回车键退出!");
                return;
            }
            //通过clientSocket接收数据  
           
            
        }
        /// 
        /**
         * 
          p.StartInfo = new System.Diagnostics.ProcessStartInfo();
             p.StartInfo.FileName = cmd;//设定程序名 
             p.StartInfo.Arguments = " shell dumpsys iphonesubinfo";
             p.StartInfo.UseShellExecute = false; //关闭shell的使用 
             p.StartInfo.RedirectStandardInput = true; //重定向标准输入 
             p.StartInfo.RedirectStandardOutput = true; //重定向标准输出 
             p.StartInfo.RedirectStandardError = true; //重定向错误输出 
             p.StartInfo.CreateNoWindow = true;//设置不显示窗口 
             p.Start();
             preimei = p.StandardOutput.ReadToEnd();
          */

        //string[] sArray = preimei.Split(new char[1] { '=' });
        //imei = sArray[2];
        //textBox1.Text = imei.Trim();
        //p.Close();
        //执行命令

    }

}

2 下面是安卓 端的 接收

package androidservice;

import android.content.Context;
import android.util.Log;

import com.example.hytf.hcyusbdemo.FileHelper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import Util.MyUtil;

public class ThreadReadWriterIOSocket implements Runnable {
    private Socket client;
    private Context context;

    ThreadReadWriterIOSocket(Context context, Socket client) {

        this.client = client;
        this.context = context;
    }

    @Override
    public void run() {
        Log.d("TAG", Thread.currentThread().getName() + "---->"
                + "a client has connected to server!");
        BufferedOutputStream out;
        BufferedInputStream in;
        try {
            /* PC端发来的数据msg */
            String currCMD = "";
            out = new BufferedOutputStream(client.getOutputStream());
            in = new BufferedInputStream(client.getInputStream());
            // testSocket();// 测试socket方法
            ConnectService.ioThreadFlag = true;
            while (ConnectService.ioThreadFlag) {
                try {
                    if (!client.isConnected()) {
                        break;
                    }

                    /* 接收PC发来的数据 */
                    Log.e("TAG", Thread.currentThread().getName()
                            + "---->" + "will read......");
                    /* 读操作命令 */
                    currCMD = readCMDFromSocket(in);
                    Log.e("TAG", Thread.currentThread().getName()
                            + "---->" + "**currCMD ==== " + currCMD);

                    /* 根据命令分别处理数据 */
                    if (currCMD.equals("1")) {
                        out.write("OK".getBytes());
                        out.flush();
                    } else if (currCMD.equals("2")) {
                        out.write("OK".getBytes());
                        out.flush();
                    } else if (currCMD.equals("3")) {
                        out.write("OK".getBytes());
                        out.flush();
                    } else if (currCMD.equals("4")) {
                        /* 准备接收文件数据 */
                        try {
                            out.write("service receive OK".getBytes());
                            out.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        /* 接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据 */
                        byte[] filelength = new byte[4];
                        byte[] fileformat = new byte[4];
                        byte[] filebytes = null;

                        /* 从socket流中读取完整文件数据 */
                        filebytes = receiveFileFromSocket(in, out, filelength,
                                fileformat);

                        // Log.e(Service139.TAG, "receive data =" + new
                        // String(filebytes));
                        try {
                            /* 生成文件 */
                            File file = FileHelper.newFile("R0013340.JPG");
                            FileHelper.writeFile(file, filebytes, 0,
                                    filebytes.length);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else if (currCMD.equals("exit")) {

                    }else{
                        String rStr = "收到:"+currCMD;
                        out.write(rStr.getBytes());
                        out.flush();
                    }
                } catch (Exception e) {
                    // try {
                    // out.write("error".getBytes("utf-8"));
                    // out.flush();
                    // } catch (IOException e1) {
                    // e1.printStackTrace();
                    // }
                    Log.e("TAG", Thread.currentThread().getName()
                            + "---->" + "read write error111111");
                }
            }
            out.close();
            in.close();
        } catch (Exception e) {
            Log.e("TAG", Thread.currentThread().getName()
                    + "---->" + "read write error222222");
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    Log.e("TAG", Thread.currentThread().getName()
                            + "---->" + "client.close()");
                    client.close();
                }
            } catch (IOException e) {
                Log.e("TAG", Thread.currentThread().getName()
                        + "---->" + "read write error333333");
                e.printStackTrace();
            }
        }
    }

    /**
     * 功能:从socket流中读取完整文件数据
     *
     * InputStream in:socket输入流
     *
     * byte[] filelength: 流的前4个字节存储要转送的文件的字节数
     *
     * byte[] fileformat:流的前5-8字节存储要转送的文件的格式(如.apk)
     *
     * */
    public static byte[] receiveFileFromSocket(InputStream in,
                                               OutputStream out, byte[] filelength, byte[] fileformat) {
        byte[] filebytes = null;// 文件数据
        try {
            in.read(filelength);// 读文件长度
            int filelen = MyUtil.bytesToInt(filelength);// 文件长度从4字节byte[]转成Int
            String strtmp = "read file length ok:" + filelen;
            out.write(strtmp.getBytes("utf-8"));
            out.flush();

            filebytes = new byte[filelen];
            int pos = 0;
            int rcvLen = 0;
            while ((rcvLen = in.read(filebytes, pos, filelen - pos)) > 0) {
                pos += rcvLen;
            }
            Log.e("TAG", Thread.currentThread().getName()
                    + "---->" + "read file OK:file size=" + filebytes.length);
            out.write("read file ok".getBytes("utf-8"));
            out.flush();
        } catch (Exception e) {
            Log.e("TAG", Thread.currentThread().getName()
                    + "---->" + "receiveFileFromSocket error");
            e.printStackTrace();
        }
        return filebytes;
    }

    /* 读取命令 */
    public static String readCMDFromSocket(InputStream in) {
        int MAX_BUFFER_BYTES = 2048;
        String msg = "";
        byte[] tempbuffer = new byte[MAX_BUFFER_BYTES];
        try {
            int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
            msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");
            tempbuffer = null;
        } catch (Exception e) {
            Log.e("TAG", Thread.currentThread().getName()
                    + "---->" + "readFromSocket error");
            e.printStackTrace();
        }
        // Log.e(Service139.TAG, "msg=" + msg);
        return msg;
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值