Android UDP广播 客户端循环发送与接收

时间:2022-01-24 09:46:30
package com.ZHouseNew.android.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.content.Context;

import com.ZHouseNew.android.Settings;
import com.ZHouseNew.android.ZHApplication;
import com.ZHouseNew.android.cache.FileCache;
import com.ZHouseNew.android.log.Logger;
import com.ZHouseNew.android.result.ScanResult;
import com.ZHouseNew.android.utils.ZHAppUtil;

/**
* udp扫描网关类
* @author zhoushuai Email: 657523985@qq.com
* Date: 14-07-14
* Time: 上午10:01
*/
public class UdpScan {
private static final String TAG = UdpScan.class.getSimpleName();
private static final int iReceivePort = 0;//接收消息的端口号
private static final int UDP_TIMEOUT = 100;//设置超时为100ms
private static final int SCAN_TIME = 1000;//扫描的时间
private static final String data = //广播发送的数据
"action=cg_do_udp&data=" + Settings.Broadcast_Data + "\n";

public static ScanResult toDo(Context context, ZHApplication zhApplication){
try {
DatagramSocket socketSend = new DatagramSocket();
DatagramSocket socketReceive;
//设置接收socket
socketReceive = (iReceivePort == 0 ? socketSend:new DatagramSocket(iReceivePort));
//设置超时
socketReceive.setSoTimeout(UDP_TIMEOUT);
//设置发送为广播
socketSend.setBroadcast(true);
//设置发送数据和接收byte,512字节大小
byte[] mDataSend = data.getBytes();
byte[] mDataReceive = new byte[512];
//设置发送的ip地址
InetAddress mAddress = InetAddress.getByName(ZHAppUtil.getBroadIP(context));
//创建发送类型的数据包
DatagramPacket sendPacket = new DatagramPacket
(mDataSend, mDataSend.length, mAddress, Settings.Broadcast_Port);

boolean isScanOver = false;
//当前时间
long currentTime = System.currentTimeMillis();
//循环扫描
while(!isScanOver)
{
long nowTime = System.currentTimeMillis();
if ((nowTime - currentTime) > SCAN_TIME)
{//扫描结束
isScanOver = true;
socketSend.close();
socketReceive.close();
break;
}

/** 发送数据包 **/
socketSend.send(sendPacket);
Logger.i(TAG, "udp send message is ok.");
//创建接收类型的数据包
DatagramPacket mPacketReceive = new DatagramPacket(
mDataReceive, mDataReceive.length);
try {
/** 接收数据包 **/
socketReceive.receive(mPacketReceive);
Logger.i(TAG, "udp receive message is ok.");
//获取反馈的ip地址
String receiveIP = mPacketReceive.getAddress().getHostAddress();
//获取反馈的数据
String receiveData = new String(mPacketReceive.getData(),
mPacketReceive.getOffset(),
mPacketReceive.getLength());
Logger.i(TAG, "receiveIP: " + receiveIP);
Logger.i(TAG, "receiveData: " + receiveData);
if (receiveData != null && !receiveData.equals(""))
{
if (zhApplication.scanDatas.size() > 0)
{
boolean isNewMessage = true;
for (String d : zhApplication.scanDatas)
{
if (d.equals(receiveData))
{
isNewMessage = false;
}
}
if (isNewMessage)
{
zhApplication.scanDatas.add(receiveData);
zhApplication.scanSocketIP.put(receiveData, receiveIP);
}
}else
{
zhApplication.scanDatas.add(receiveData);
zhApplication.scanSocketIP.put(receiveData, receiveIP);
}
}
} catch (Exception e) {
//内部捕捉异常,防止跳出循环
Logger.e(TAG, "udp receive timeout.");
}
}
//扫描结束后
if (zhApplication.scanDatas.size() > 0)
{
//存入文本缓存
int dLen = zhApplication.scanDatas.size();
for (int i = 0; i < dLen; i++)
{
FileCache.saveFileCache(Settings.SCAN_DATAS + i, zhApplication.scanDatas.get(i));
}
for (int i = 0; i < dLen; i++)
{
FileCache.saveFileCache(zhApplication.scanDatas.get(i), zhApplication.scanSocketIP.get(i));
}
zhApplication.scanResult.setDatas(zhApplication.scanDatas);
zhApplication.scanResult.setIps(zhApplication.scanSocketIP);
return zhApplication.scanResult;
}

} catch (Exception e) {
Logger.e(TAG, "UDP scan is failure",e);
}
return null;
}
}
udp循环广播和接收,存储不同的数据和其对应的ip的地址,用于后面区别连接