I'm starting to code with MulticastSocket, trying to make a simple app with a client and a server to send messages.
The code I have for the server:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
public class Servidor {
private static MulticastSocket ms;
public static void main(String[] args) throws IOException{
InetAddress sessAddr = InetAddress.getByName("224.2.76.24");
try{
sessAddr = InetAddress.getByName("224.2.76.24");
ms = new MulticastSocket(5500);
ms.joinGroup(sessAddr);
while (true)
{
byte[] mensaje = new byte[1024];
mensaje = "aa".getBytes();
DatagramPacket dp = new DatagramPacket(mensaje, mensaje.length,sessAddr,5500);
ms.send(dp);
}
}
catch (SocketException se) {
System.err.println(se);
}
ms.leaveGroup(sessAddr);
}
}
And this on the client:
package com.example;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class ClienteMultiCast extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView Mensaje;
Mensaje =(TextView)findViewById(R.id.Mensaje);
InetAddress ia = null;
byte[] buffer = new byte[65535];
MulticastSocket ms = null;
int port = 5500;
try {
ia = InetAddress.getByName("224.2.76.24");
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,ia,port);
ms = new MulticastSocket(port);
ms.joinGroup(ia);
while (true) {
ms.receive(dp);
String s = new String(dp.getData(),0,dp.getLength());
Mensaje.setText(s);
}
} catch (UnknownHostException e) {Mensaje.setText(e.getMessage());} catch (IOException e) {Mensaje.setText(e.getMessage()); }
try {
ms.leaveGroup(ia);
} catch (IOException e) {
Mensaje.setText(e.getMessage());
}
}
}
The problem is that when I start both, nothing happens. The client doesn't get any message.
Any idea what's wrong?
It appears that Multicast support in Android is not as solid as some of use might hope. See http://codeisland.org/2012/udp-multicast-on-android/
Ie whether it actually works out or may be device dependent. It is not working on my Nexus5.
https://code.google.com/p/android/issues/detail?id=51195
Diego,
By default, the Android WiFi stack filters out multicast packets. Take a look at http://developer.android.com/reference/android/net/wifi/WifiManager.MulticastLock.html.
You need something along the lines of: