Android与PC通过USB连接通信(一)


原理

通过在Android设备与PC之间通过USB建立socket连接,以Android作为服务器,PC作为客户端,通过adb进行转发通信。

客户端代码及分析

package com.geo.main;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.InterruptedIOException;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;import com.geo.util.FileHelper;import com.geo.util.MyUtil;/** * usb与pc通信,通过adb端口转发方式 */public class testPcClient{public static void main(String[] args) throws InterruptedIOException{try{// adb 指令,在服务器开启后建立连接Runtime.getRuntime().exec("adb shell am broadcast -a NotifyServiceStop");Thread.sleep(3000);Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086"); // 端口转换Thread.sleep(3000);Runtime.getRuntime().exec("adb shell am broadcast -a NotifyServiceStart");Thread.sleep(3000);} catch (Exception e){e.printStackTrace();}Socket socket = null;try{/*建立socket连接*/InetAddress serveraddr = null;serveraddr = InetAddress.getByName("127.0.0.1");System.out.println("TCP C: Connecting...");socket = new Socket(serveraddr, 12580);String str = "hi,chenhl";System.out.println("TCP C: RECEIVE");BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());BufferedInputStream in = new BufferedInputStream(socket.getInputStream());BufferedReader br = new BufferedReader(new InputStreamReader(System.in));boolean flag = true;while (flag){System.out.print("请输入file传递文件,退出输入exit:");String strWord = br.readLine();// if (strWord.equals("file")){/* 发送命令,out为发送给服务器的命令*/out.write("file".getBytes());out.flush();System.out.println("send file finish sending the CMD:");/* 服务器反馈准备接受,in为服务器的反馈 */String strFormsocket = readFromSocket(in);System.out.println("service ready receice data:UPDATE_CONTACTS:" + strFormsocket);byte[] filebytes = FileHelper.readFile("test1.txt");/*FileHelper为一个class,readFile将此处的test1.txt内容读取为byte[]格式test1.txt文件路径在FileHelper内设置*/System.out.println("fileszie = " + filebytes.length);/* MyUtil将整数转换为4字节byte数组 */byte[] filelength = new byte[4];filelength = MyUtil.intToByte(filebytes.length);byte[] fileformat = null;fileformat = ".png".getBytes();System.out.println("fileformat length=" + fileformat.length);/* 字节流中前4字节为文件长度,4字节文件格式,以后是文件流 *//* 注意如果write里的byte[]超过socket的缓存,系统会自动分包写过去,所以对方要循环写完 *//*一些文件属性的输出*/out.write(filelength);out.flush();String strok1 = readFromSocket(in);System.out.println("service receive filelength :" + strok1);System.out.println("write data to android");out.write(filebytes);out.flush();System.out.println("*********");/* 服务器反馈:接收成功 */String strread = readFromSocket(in);System.out.println(" send data success:" + strread);System.out.println("=============================================");} else if (strWord.equalsIgnoreCase("EXIT")){out.write("EXIT".getBytes());out.flush();System.out.println("EXIT finish sending the data");String strFormsocket = readFromSocket(in);System.out.println("the data sent by server is:/r/n" + strFormsocket);flag = false;System.out.println("=============================================");}}} catch (UnknownHostException e1){System.out.println("TCP ERROR1:" + e1.toString());} catch (Exception e2){System.out.println("TCP ERROR2:" + e2.toString());} finally{try{if (socket != null){socket.close();System.out.println("socket.close()");}} catch (IOException e){System.out.println("TCP ERROR3:" + e.toString());}}}/* 从inputestream流中读数据*/public static String readFromSocket(InputStream in){int MAX_BUFFER_BYTES = 4000;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){e.printStackTrace();}return msg;}}

分析及总结

此段代码为PC端的客户端代码,直接在PC端进行运行,在控制台输入指令,通过socket连接以adb指令的USB转发来传递数据,但是需要android设备首先开启服务端才能成功建立socket,全程需要将PC与android设备进行USB连接。

更多相关文章

  1. Android 自定义View及其在布局文件中的使用示例(三):结合Android
  2. Android 4.4 SD卡文件读写变化
  3. Android 自动编译、打包生成apk文件 2 - 使用原生Ant方式
  4. Android学习之路(一)之 Android文件简单介绍
  5. Android 上如何移植live555生成库文件
  6. android访问服务器端上传及服务器端接收 .
  7. Android NDK 使用第一步,编译c文件,声明jni并调用。
  8. Android中文件的读写

随机推荐

  1. 深入理解C#设计模式之策略模式 角色具体
  2. 设计一个c++ 通用链表:实现多态双向的功能
  3. 采用 C# 编写的学委助手详解及实例
  4. C++实现贪吃蛇游戏的详细步骤及实战演示
  5. Thinking in C++ 第一卷阅读全书笔记重点
  6. C/C++区别有哪些?很多人都不知道的比较方
  7. 原来斐波拉契数列还有这种写法,你知道吗?
  8. C++_STL常用容器总结:对组pair中关联容器
  9. c/c++字符串函数是什么类型和它是如何转
  10. 详细介绍C# 中 ASP.NET Web API 的 ROC