我有一个Android手机充当客户端并发送组播数据包到239.255.255.253
代码是
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t=new Thread(new Multi());
t.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
class Multi implements Runnable
{
@Override
public void run() {
// TODO Auto-generated method stub
try {
InetAddress ip=InetAddress.getByName("239.255.255.253");
int port=4270;
//Create a Multicast socket
MulticastSocket sock=new MulticastSocket();
String msg="Hello All";
DatagramPacket pack=new DatagramPacket(msg.getBytes(),msg.length(),ip,port);
sock.send(pack);
sock.close();
System.out.println("Packet sent");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我的android清单文件是
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multicast"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.multicast.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>
</application>
</manifest>
Android和PC都通过路由器连接
在我的电脑上运行服务器代码,它只接收239.255.255.253和的数据包 224.0.0.2。
服务器代码
import java.io.*;
import java.net.*;
class receiver
{
public static void main(String args[])
{
try
{
//get the multicast ip
InetAddress ip1 = InetAddress.getByName("239.255.255.253");
InetAddress ip2 = InetAddress.getByName("224.0.0.2");
int port=4270;
MulticastSocket sock=new MulticastSocket(port);
//join the multicast group
sock.joinGroup(ip1);
sock.joinGroup(ip2);
while(true)
{
//create a datagram packet in which u will receive the msg
byte[] buffer=new byte[100];
DatagramPacket pack=new DatagramPacket(buffer,buffer.length);
sock.receive(pack);
InetAddress ip= pack.getAddress();
System.out.print(ip+":");
System.out.println("the message received from the sender is "+new String(buffer));
}
//sock.close();
}
catch(Exception e){
}
}
}
我无法在PC上接收任何数据包,但是当我将客户端的多播地址更改为“224.0.0.2”时,它工作正常。任何人都可以帮我解决这个问题