MulticastSocket是对等的关系,也就是他们通过IP多点组播保留的地址来相互接收在这个组的Socket发送的消息
我写了一个例子,MultiSocketB是一个service,用于先接收再发送,MultiSocketA用于先发送再接收,完成这一动作后退出
记得要加使用网络的权限
<uses-permission android:name="android.permission.INTERNET" />先看MultiSocketA
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.multicastsocketsend" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.multicastsocketsend.MultiSocketA" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
package com.example.multicastsocketsend; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; /** * @author lijinwei * 本应用用于实现IP多点广播 * 若要使用多点广播时,则需要让一个数据报标有一组目标主机地址,当数据报发出后,整个组的所有主机都能收到该数据报。 * IP多点广播(或多点发送)实现了将单一信息发送到多个接收者的广播,其思想是设置一组特殊网络地址作为多点广播地址,每一个多点广播地址都被看做一个组, * 当客户端需要发送、接收广播信息时,加入到该组即可。 */ public class MultiSocketA extends Activity { protected static final String TAG = "MultiSocketA"; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //通过Handler启动线程 HandlerThread handlerThread = new HandlerThread("MultiSocketA"); handlerThread.start(); mHandler = new Handler(handlerThread.getLooper()); mHandler.post(mRunnable); } private Runnable mRunnable = new Runnable() { public void run() { Log.v(TAG, "run..."); try { sendMultiBroadcast(); } catch (Exception e) { e.printStackTrace(); } } private void sendMultiBroadcast() throws IOException { Log.v(TAG, "sendMultiBroadcast..."); /* * 实现多点广播时,MulticastSocket类是实现这一功能的关键,当MulticastSocket把一个DatagramPacket发送到多点广播IP地址, * 该数据报将被自动广播到加入该地址的所有MulticastSocket。MulticastSocket类既可以将数据报发送到多点广播地址, * 也可以接收其他主机的广播信息 */ MulticastSocket socket = new MulticastSocket(8600); //IP协议为多点广播提供了这批特殊的IP地址,这些IP地址的范围是224.0.0.0至239.255.255.255 InetAddress address = InetAddress.getByName("224.0.0.1"); /* * 创建一个MulticastSocket对象后,还需要将该MulticastSocket加入到指定的多点广播地址, * MulticastSocket使用jionGroup()方法来加入指定组;使用leaveGroup()方法脱离一个组。 */ socket.joinGroup(address); /* * 在某些系统中,可能有多个网络接口。这可能会对多点广播带来问题,这时候程序需要在一个指定的网络接口上监听, * 通过调用setInterface可选择MulticastSocket所使用的网络接口; * 也可以使用getInterface方法查询MulticastSocket监听的网络接口。 */ //socket.setInterface(address); DatagramPacket packet; //发送数据包 Log.v(TAG, "send packet"); byte[] buf = "Hello I am MultiSocketA".getBytes(); packet = new DatagramPacket(buf, buf.length, address, 8601); socket.send(packet); //接收数据 Log.v(TAG, "receiver packet"); byte[] rev = new byte[512]; packet = new DatagramPacket(rev, rev.length); socket.receive(packet); Log.v(TAG, "get data = " + new String(packet.getData()).trim()); //不加trim,则会打印出512个byte,后面是乱码 //退出组播 socket.leaveGroup(address); socket.close(); } }; }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.multicastsocketreceiver" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.multicastsocketreceiver.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MultiSocketB" /> </application> </manifest>
package com.example.multicastsocketreceiver; import android.os.Bundle; import android.app.Activity; import android.content.Intent; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(); intent.setClass(this, MultiSocketB.class); this.startService(intent); } }
package com.example.multicastsocketreceiver; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.util.Log; public class MultiSocketB extends Service { protected static final String TAG = "MultiSocketB"; private Handler mHandler; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.v(TAG, "onCreate"); // 通过Handler启动线程 HandlerThread handlerThread = new HandlerThread("MultiSocketB"); handlerThread.start(); mHandler = new Handler(handlerThread.getLooper()); mHandler.post(mRunnable); } private Runnable mRunnable = new Runnable() { public void run() { Log.v(TAG, "run..."); try { receiveMultiBroadcast(); } catch (Exception e) { e.printStackTrace(); } } }; protected void receiveMultiBroadcast() throws IOException { Log.v(TAG, "receiveMultiBroadcast..."); MulticastSocket socket = new MulticastSocket(8601); InetAddress address = InetAddress.getByName("224.0.0.1"); socket.joinGroup(address); DatagramPacket packet; // 接收数据 Log.v(TAG, "receiver packet"); byte[] rev = new byte[512]; packet = new DatagramPacket(rev, rev.length); socket.receive(packet); String receiver = new String(packet.getData()).trim(); //不加trim,则会打印出512个byte,后面是乱码 Log.v(TAG, "get data = " + receiver); //发送数据包 Log.v(TAG, "send packet"); String process_receiver = "I am MultiSocketB, I got " + receiver; byte[] buf = process_receiver.getBytes(); packet = new DatagramPacket(buf, buf.length, address, 8600); socket.send(packet); //退出组播 socket.leaveGroup(address); socket.close(); } }