Reputation: 1730
I'm programming an Android application allows to send messages between devices which are connected in the same local network. I've finished the socket programming part, each device can be a server or a client, one client only allow to connect with one server at a time (and vice versa). The problem is I need to know the IP address of the server I want to connect, then input it by hand on the client side.
I'm trying to establish a feature like in Multiplayer mode of game: you press "Show" button, and all the hosts (in my app they are the servers) which are avaiable will be displayed, then I can choose the host I want. But I have no idea how to achieve it, or where to start.
Any help will be appreciated. Thank you very much!
Upvotes: 0
Views: 198
Reputation: 72321
You should also create a DatagramSocket
which will be used for broadcasting, on a different port, and every device that wants to be an Server
should broadcast a packet with it's ip. You should look at All about Datagrams altough it does not contain an example of broadcast. For example to send a broadcast you should take a look at the following code :
DatagramSocket mServerSocket = new DatagramSocket(PORT);
InetAddress broadcastAddress=InetAddress.getByName("255.255.255.255");
byte[] data=new byte[1024];
data="your_data_string_example".getBytes();
DatagramPacket packet=new DatagramPacket(sendData,
sendData.length,broadcastAddress,PORT);
mServerSocket.setBroadcast(true);
mServerSocket.send(packet);
Upvotes: 1