Search code examples
androidsocketsadb

How to programmatically broadcast a String message from PC to multiple USB-attached Android phones?


My Goal: I want to programmatically broadcast a String message (containing the system time of PC) from PC to two USB-attached Android phones.

My Attempt:

(1) I have two Android phones attached to a computer via USB.

adb-devices

(2) I use the "adb -s forward" commands to set up forwarding of the computer port 38300 to device ports 38300.

adb-forward

(3) Programming for the Android phones: Basically, I create a ServerSocket on the port 38300, set its timeout, and call the accept() method.

(4) Programming for the PC: I create the Socket using this.pchost_socket = new Socket("localhost", 38300);, and the message containing the system time of PC is sent using oos = new ObjectOutputStream(this.pchost_socket.getOutputStream()); oos.writeObject(msg);.

Problem:

Only one Android phone (in this case, it is the phone 067125a40acc819e) has received the message.

(1) Is this the default behaviour of communication via USB/ADB?
(2) How to programmatically broadcast a String message from PC to multiple USB-attached Android phones? (It is not necessary to use Socket programming.)


Solution

  • You can't multicast ports on the host computer via ADB; your second adb forward command steals port 38300 from the first device and assigns it to the second. What you could do if you want to move forward with this solution is design your system to use a range of ports, starting at 38300 (or whatever you like). Device 1 gets 38300, device 2 gets 38301, device 3 gets 38302, and so on. On the device side, use the same port number for all devices, to simplify your app design.

    adb -s <device1> forward tcp:38300 tcp:38300
    adb -s <device2> forward tcp:38301 tcp:38300
    adb -s <device3> forward tcp:38302 tcp:38300
    adb -s <device4> forward tcp:38303 tcp:38300
    

    You will then need your PC software to connect to all of the open ports on the PC and send the message.