ここで説明するように、Android Emulatorはマルチキャストをサポートしていないため、状況に応じて回避策を講じようとしています。
これを行うために、マルチキャストパケットをリッスンし、それをローカルホストアドレスに繰り返す小さなJavaプログラムを作成しました。この「マルチキャストリピーター」はAndroidエミュレーターと同じマシンで実行されているため、マルチキャストパケットをエミュレーターにループバックできることを期待していました。残念ながら、これは機能していないようです。
これは、Eclipseとエミュレーターの外部で実行する「マルチキャストリピーター」メソッドです。時刻を含むUDPパケットを送信するネットワーク上の別のマシンからUDPメッセージを受信することを確認しました。
public static void main(String[] args) throws IOException{
boolean loop = true;
MulticastSocket socket = new MulticastSocket(4446);
InetAddress address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);
DatagramSocket txSocket = new DatagramSocket(); // UDP socket to re transmit on
DatagramPacket packet;
while (loop){
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Quote of the Moment: " + received);
packet = new DatagramPacket(received.getBytes(), received.getBytes().length, InetAddress.getLocalHost, 4448);
txSocket.send(packet);
}
socket.leaveGroup(address);
socket.close();
}
そして、これはAndroidアプリで実行される私の「レシーバー」コードです。
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
txtView.append("Network connected.\r\n");
WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock wmmc = wm.createMulticastLock("MulticastTest");
if (wmmc.isHeld()){
txtView.append("Multicast lock is held\r\n");
}else{
txtView.append("Multicast lock NOT held, attempting to acquire.\r\n");
wmmc.acquire();
}
if (wmmc.isHeld()){
try{
DatagramSocket rxSocket = new DatagramSocket(4448);
rxSocket.setSoTimeout(5000);
DatagramPacket packet;
// get a few quotes
for (int i = 0; i < 5; i++) {
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
try{
rxSocket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
txtView.append(received + "\r\n");
} catch (InterruptedIOException ex){
txtView.append("Socket timed out.\r\n");
}
//System.out.println("Quote of the Moment: " + received);
}
//socket.leaveGroup(address);
//socket.close();
}catch (Exception ex){
txtView.append(ex.toString() + "\r\n");
}finally{
wmmc.release();
}
}else{
txtView.append("Could not acquire multicast lock.\r\n");
}
}else{
txtView.append("Network NOT connected");
}
残念ながら、受信ソケットはタイムアウトします。'10.0.2.2'(ここで説明)にバインドしようとしましたが、これは例外をスローしますが、これはエミュレーターから開発マシンにアクセスしたい場合にのみ有用であるように見えますが、開発マシンからエミュレーターにアクセスしたい場合にのみ役立ちます。誰か提案はありますか?