Skip to content Skip to sidebar Skip to footer

Android Bluetooth Multiple Clients To One Host

Here is the situation. I'm creating an Android that utilises Bluetooth to update connected clients of each other's status. The idea is for the host of the Bluetooth connection to h

Solution 1:

The reason you need a thread for each connection is this:

Imagine you have two opened sockets, sock1 and sock2. To read from those sockets, you might call something like

InputStream in1 = sock1.getInputStream();
InputStream in2 = sock2.getInputStream();

Now, to read from sock1, you call

in1.read(buffer);

where "buffer" is a byte array, in which you store the bytes you read.

However, read() is a blocking call - in other words, it doesn't return, and you don't get to execute the next line, until there are some bytes to read(). So if you try to read sock1, you'll never get to read sock2, and vice versa, if they're in the same thread.

Thus if you have one thread per connection, each thread can call read(), and wait for input. If input comes while one of the other threads is executing, it waits until that thread's turn comes up, and then proceeds.

To actually implement this, all you need to do is stick the code to handle one connection into a class that extends Thread.

There are lots of details involved - I would suggest the Android BluetoothChat sample as a good tutorial.


Post a Comment for "Android Bluetooth Multiple Clients To One Host"