Android IP多播MulticastSocket UDP实现

举报
aiot_bigbear 发表于 2022/09/25 05:13:23 2022/09/25
【摘要】 UDP多播 在智能设备领域 用处很多,WIFI密码配置等。 以下是自己动手实现的一个例子,算是总结下相关方面知识了,温故而知新。 package com.jy.viewpagefragment; import java.io.IOException; import java.net.DatagramPacket; import ...

UDP多播 在智能设备领域 用处很多,WIFI密码配置等。

以下是自己动手实现的一个例子,算是总结下相关方面知识了,温故而知新。

package com.jy.viewpagefragment;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;


import com.jy.example2.R;
import com.jy.example2.R.id;
import com.jy.example2.R.layout;
import com.jy.example2.R.menu;


import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class UdpMultiMainActivity extends Activity {
//private InetAddress group;
private Handler handler; // 声明一个Handler对象

private static final String TAG="UdpMultiMainActivity";   
private static final int MULTICAST_PORT=5111;   
//private static final String GROUP_IP="224.5.0.7";
//239.255.255.250
private static final String GROUP_IP="239.255.255.250";

private static byte[] sendData;   
 
     MulticastSocket multicastSocket = null;
     InetAddress group = null;
     MulticastLock mlock;
   static{   
       sendData=new byte[4];   
       // 0xEE78F1FB   
       sendData[3] = (byte) 0xEE;   
       sendData[2] = (byte) 0x78;   
       sendData[1] = (byte) 0xF1;   
       sendData[0] = (byte) 0xFB;   
   } 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_udp_multi_main);


// 实例化一个Handler对象
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 更新UI
TextView tv = (TextView) findViewById(R.id.udptext); // 获取TextView组件
if (msg.what == 0x101) {
tv.setText(msg.getData().getString("title")); // 设置标题
//iv.setImageResource(path[msg.arg1]); // 设置要显示的图片
}
super.handleMessage(msg);
}


};
//private InetAddress group;


//WifiManager wm=(WifiManager)getSystemService(WIFI_SERVICE);
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
mlock=wm.createMulticastLock("mygroup");
mlock.acquire();



//创建多播组
try {
multicastSocket = new MulticastSocket(MULTICAST_PORT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}   
        try {
        //multicastSocket.setLoopbackMode(true);

//设置本MulticastSocket发送的数据报被回送到自身  
multicastSocket.setLoopbackMode(false);  
Log.d("multicastSocket","setLoopbackMode false ");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}   
        
try {
group = InetAddress.getByName(GROUP_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}   
        try {
multicastSocket.joinGroup(group);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

        
        Timer timer=new Timer();
      //  timer.schedule(new MyTimerTask(),3000);
        timer.schedule(new MyTimerTask(), 3 * 1000, 1 * 1000); //利用timer.schedule方法
        
        Thread t = new Thread(new MyThread()); // 创建新线程
t.start(); // 开启线程

       // new Thread().start();
        
       // new MyThread.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.udp_multi_main, menu);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

//时间任务
class MyTimerTask extends TimerTask{
//byte[] bs = new byte[1024];

  
@Override
public void run() {
// TODO Auto-generated method stub
//DatagramPacket packet = new DatagramPacket(sendData,sendData.length, group, Integer.valueOf(pro.getProperty("multicast_port")));
String ip=null;  
    //   byte[] multicast_string="multicastSocket";
       DatagramPacket packet=new DatagramPacket(sendData, sendData.length,group,MULTICAST_PORT);
      // for(;;){   
        try {
       
        multicastSocket.send(packet);   
            Log.d(TAG,">>>send packet ok");   
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG,">>>send packet IOException");  
}
    //   }
}



}
//Thread t = new Thread(new Runnable() 
class MyThread implements Runnable{
DatagramPacket packet=null;
byte[] receiveData=new byte[256];  
String ip=null;  
// DatagramPacket packet=new DatagramPacket(sendData, sendData.length,group,MULTICAST_PORT);   
public void run() {     
 
Log.d("run==","MyThread start");
packet=new DatagramPacket(receiveData, receiveData.length);   
try {
multicastSocket.receive(packet);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}   
     
Message m = handler.obtainMessage(); // 获取一个Message
m.arg1 = 1; // 保存要显示广告图片的索引值

m.what = 0x101; // 设置消息标识

Bundle bundle = new Bundle(); // 获取Bundle对象
bundle.putString("title", "get data"); // 保存标题
m.setData(bundle); // 将Bundle对象保存到Message中
handler.sendMessage(m); // 发送消息



String packetIpAddress=packet.getAddress().toString();   
packetIpAddress=packetIpAddress.substring(1, packetIpAddress.length());   
Log.d(TAG,"packet ip address: "+packetIpAddress);   
//03-10 14:40:53.433: D/UdpMultiMainActivity(31357): packet ip address: 192.168.123.28

/*
StringBuilder packetContent=new StringBuilder();   
for(int i=0;i<receiveData.length;i++){   
if(receiveData[i]==0){   
break;   
}   
packetContent.append((char)receiveData[i]);   
}   
ip=packetContent.toString();   
Log.d(TAG,"packet content ip is: "+ip);   
*/
//if(ip.equals(packetIpAddress)){   
int flag=1;
if(flag==1){  
Log.d(TAG,"find server ip address: "+ip);   
//break;   
}else{   
Log.d(TAG,"not find server ip address, continue …");   
try {   
Thread.sleep(1000);   
} catch (InterruptedException e) {  
e.printStackTrace();
}   
}   
}

}
private void closeWifiBrocast(){
if (mlock != null){
mlock.release();
mlock = null;
Log.e("closeWifiBrocast","closeWifiBrocast");
}
}
protected void onDestroy() {
closeWifiBrocast();


//timer.cancel(); //退出计时器

// flag= false;
super.onDestroy();
}
}

文章来源: blog.csdn.net,作者:悟空胆好小,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/xushx_bigbear/article/details/44175631

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。