# AndroidUSBSocketDemo **Repository Path**: guchuanhang/AndroidUSBSocketDemo ## Basic Information - **Project Name**: AndroidUSBSocketDemo - **Description**: Android 通过USB数据线 完成socket通信(不需要手机和PC的IP信息) - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 15 - **Forks**: 3 - **Created**: 2020-06-05 - **Last Updated**: 2024-11-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # AndroidUSBSocketDemo 主要用于演示通过adb端口转发功能实现socket通信。此实例Demo包含两部分AndroidApp、JavaPCApp. ## 准备工作 修改JavaPCApp 对应java_client分支 * 配置PCHost.java 为启动的Main * PCHost.java ADBExecutor() 参数为自己电脑中adb的路径 ADBExecutor adb_executor = new ADBExecutor("D:\\\\Android_SDK\\\\platform-tools\\\\adb.exe"); ## AndroidApp 使用Android Studio3.6.3进行开发,主要作用是开启一个ServerSocket等待PC client进行连接,然后进行简单的socket通信。 ## JavaPCApp 使用Intellij IDEA 进行开发,主要作用是通过adb查询当前已经连接的设备,并设置端口转发,然后,进行简单的socket通信。 ## CShapeClientSolution 对应cshape_client ## 运行实例方法 1. 运行AndroidApp 2. 运行JavaPCApp 通过控制台查看socket通信内容 AndroidApp控制台打印 安卓: 你好猪娃! JavaPCApp控制台打印 猪娃: 你好,安卓 ## blog 关于实现方式的进一步讲解请参考: [Android Adb USB Socket 通信](https://blog.csdn.net/guchuanhang/article/details/106599812 ) ## 参考内容 [安卓与PC使用USB一种Socket通信方案]((http://www.cnblogs.com/sxdcgaq8080/p/7894828.html)) ## 注意事项 使用JavaClientApp 和 CShapeClient 有一点不同就是文字的编码方式,对于JavaClientApp,直接使用 dataOutputStream.writeUTF("安卓: 你好猪娃!"); 对于CShapeClient需要修改以字节码的方式读入,然后使用 byte[] receive = new byte[1024]; int length = ClientSocket.Receive(receive); // length 接收字节数组长度 string text = Encoding.UTF8.GetString(receive); Console.WriteLine("接收消息为:" + text); string sendMsg = "C#: 你好Android"; byte[] msgBytes = Encoding.UTF8.GetBytes(sendMsg); ClientSocket.Send(msgBytes); 同时Server端也需要调整为: String sndMsg = "安卓: 你好PC!"; byte[] sndBytes = sndMsg.getBytes(Charset.forName("utf-8")); outputStream.write(sndBytes); outputStream.flush(); byte[] rcvBytes = new byte[1024]; int rcvLen = inputStream.read(rcvBytes); String rcvMsg = new String(rcvBytes, 0, rcvLen, Charset.forName("utf-8")); System.out.println(rcvMsg); ## License ``` Copyright 2020, guchuanhang Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ```