加载中…
正文 字体大小:

android发送UDP广播及在PC上接受广播数据

(2011-07-15 17:51:29)
标签:

杂谈

分类: 技术

android端,发送UDP广播包:

 

public class WifiBroadcastActivity extends Activity {
 private static String LOG_TAG="WifiBroadcastActivity";
 private boolean start = true;
 private EditText IPAddress;
 private String address;
 public static final int DEFAULT_PORT = 43708;
 private static final int MAX_DATA_PACKET_LENGTH = 40;
    private byte[] buffer = new byte[MAX_DATA_PACKET_LENGTH];
    Button startButton;
    Button stopButton;
   
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        IPAddress = (EditText) this.findViewById(R.id.address );
        startButton = (Button) this.findViewById(R.id.start);
        stopButton = (Button) this.findViewById(R.id.stop);
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
       
        address = getLocalIPAddress();
  if( address != null ){
   IPAddress.setText( address );
  }
  else {
   IPAddress.setText("Can not get IP address");
   
   return;
  }
  EditText numberEdit = (EditText) findViewById(R.id.number);
  numberEdit.setText(number);
       
        startButton.setOnClickListener( listener );
        stopButton.setOnClickListener( listener );
    }
   
    private String number = getRandomNumber();
    private View.OnClickListener listener = new View.OnClickListener() {
  
  @Override
  public void onClick(View v) {
   if( v == startButton ){    
    start = true;
    new BroadCastUdp(number).start();
    startButton.setEnabled( false );
    stopButton.setEnabled(true);
   }else if( v == stopButton ){
    start = false;
    startButton.setEnabled(true);
    stopButton.setEnabled(false);
   }
  }
 };
       
    private String getLocalIPAddress(){
     try {
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();  
       en.hasMoreElements();) { 

       NetworkInterface intf = en.nextElement(); 

       for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 

        InetAddress inetAddress = enumIpAddr.nextElement(); 

        if (!inetAddress.isLoopbackAddress()) {
         return inetAddress.getHostAddress().toString();
        }
       }
      }
     } catch (SocketException ex){
      Log.e(LOG_TAG, ex.toString()); 
     

     return null;
    }
   
    private String getRandomNumber(){
     int num = new Random().nextInt(65536);
     String numString = String.format("x", num);
     return numString;
    }
   
    public class BroadCastUdp extends Thread{
     private String dataString;
     private DatagramSocket udpSocket;
     public BroadCastUdp( String dataString ) {
   this.dataString = dataString;
  }
     
     public void run(){
      DatagramPacket dataPacket = null;
      
      try {
       udpSocket = new DatagramSocket(DEFAULT_PORT );
       
       dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);      
       byte[] data = dataString.getBytes();
    dataPacket.setData( data );
    dataPacket.setLength( data.length );
    dataPacket.setPort( DEFAULT_PORT );   
   
    InetAddress broadcastAddr;
   
    broadcastAddr = InetAddress.getByName("255.255.255.255");
    dataPacket.setAddress(broadcastAddr);
   } catch (Exception e) {
    Log.e(LOG_TAG, e.toString());
   }

   while( start ){
    try {     
     udpSocket.send(dataPacket);
     sleep( 10 );
    } catch(Exception e) {
     Log.e(LOG_TAG, e.toString());
       
   }
   
   udpSocket.close();
     }
    }
}

 

 

 

PC端,接收UDP广播数据:

public class WifiListener {
 private static DatagramSocket udpSocket;
 private static byte[] data = new byte[256];
 private static DatagramPacket udpPacket = new DatagramPacket( data, 256 );
 
 public static void main(String[] args) {
  try {
   udpSocket = new DatagramSocket( 43708 );
  } catch (SocketException e) {
   System.out.println( e.toString());
  }
  
  while( true ){
   try {    
    udpSocket.receive(udpPacket);
   } catch (Exception e) {
    System.out.println( e.toString());
   }
   
   if( udpPacket.getLength() != 0 ){
    String codeString = new String( data, 0, udpPacket.getLength() );
    System.out.println( codeString );
   }
  }
 }
}

0

阅读 评论 收藏 转载 喜欢 打印举报
已投稿到:
  • 评论加载中,请稍候...
发评论

       

    发评论

    以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

      

    新浪BLOG意见反馈留言板 不良信息反馈 电话:4006900000 提示音后按1键(按当地市话标准计费) 欢迎批评指正

    新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

    新浪公司 版权所有