Android - adb forward实现PC和App的Socket通讯 博客分类: 【57】、Android
程序员文章站
2024-03-19 12:25:52
...
PC端的XX助手和手机App的通讯原理:
# 把PC端8000端口的数据, 转发到Android端的9000端口上. adb forward tcp:8000 tcp:9000
执行命令后, PC端的8000端口会被 adb
监听, 这个时候我们只需要往8000端口写数据, 这个数据就会发送到手机端的9000端口上.
PC端程序
把输入内容发送给8000端口
public class PCClient { public static void main(String[] args) throws IOException { System.out.println("任意字符, 回车键发送Toast"); Scanner scanner = new Scanner(System.in); while (true) { String msg = scanner.next(); sendToast(msg); } } public static void sendToast(String msg) throws IOException { Socket socket = new Socket("127.0.0.1", 8000); DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(msg); socket.close(); } }
Android端程序
监听9000端口, 把收到的数据, Toast在屏幕上
public class MainActivity extends AppCompatActivity { private static final String TAG = "ServerThread"; ServerThread serverThread; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Toast.makeText(getApplicationContext(), msg.getData().getString("MSG", "Toast"), Toast.LENGTH_SHORT).show(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serverThread = new ServerThread(); serverThread.start(); } @Override protected void onDestroy() { super.onDestroy(); serverThread.setIsLoop(false); } class ServerThread extends Thread { boolean isLoop = true; public void setIsLoop(boolean isLoop) { this.isLoop = isLoop; } @Override public void run() { Log.d(TAG, "running"); ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(9000); while (isLoop) { Socket socket = serverSocket.accept(); Log.d(TAG, "accept"); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); String msg = inputStream.readUTF(); Message message = Message.obtain(); Bundle bundle = new Bundle(); bundle.putString("MSG", msg); message.setData(bundle); handler.sendMessage(message); socket.close(); } } catch (Exception e) { e.printStackTrace(); } finally { Log.d(TAG, "destory"); if (serverSocket != null) { try { serverSocket.close(); } catch (Exception e) { e.printStackTrace(); } } } } } }
运行效果
源码
实际开发中的问题
- Android端的程序 有可能被干掉
- adb forward 有可能会被干掉
由于连接不稳定性,判断真正连接成功的方法,只有轮询收发握手数据包:
C发送一个数据包,等待S回复;
C如果收到了S的回复包,说明连通。
如果接收超时,则认为没有连通.
在没有连通的情况下,需要重新建立Socket,并Connect(),然后再尝试握手。
作者:口袋FPV 链接:http://www.jianshu.com/p/fee5b31774be 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。