Android Bluetooth multiple clients to one host

…衆ロ難τιáo~ 提交于 2019-12-11 01:06:31

问题


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 hold a multi-dimensional array holding all of these stats. Each time a client updates the host of their new status, the host then update the data in the array and then sends this to all the clients.

Of course, this all sounds like milk and cookies to me, but unfortunately it is not. I understand that I need to have a Bluetooth socket on each end and one of them needs to be a host socket. So, get one connection done seems pretty straight forward. But what if I then want to accept more connections? I've been reading around and apparently I have to create a new thread for each connection. I don't see how that would work, could someone please explain this?


回答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.



来源:https://stackoverflow.com/questions/9694840/android-bluetooth-multiple-clients-to-one-host

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!