Android sends UDP packets and Java applications to answer

Source: Internet
Author: User

From: http://blog.sina.com.cn/s/blog_6c0a8fbb0100s3k5.html

In my reference blog, I forgot to add the network permission (<uses-Permission Android: Name = "android. Permission. Internet"> </uses-Permission>) to manifest)

Android code:

package com.example.sendudpbroadcasttest;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;import java.util.Random;import android.os.Bundle;import android.app.Activity;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.support.v4.app.NavUtils;public class MainActivity 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.activity_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;}        startButton.setOnClickListener( listener );        stopButton.setOnClickListener( listener );    }private String number = getRandomNumber();private View.OnClickListener listener = new View.OnClickListener() {@Overridepublic 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();    }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.activity_main, menu);        return true;    }    }

Java code:

import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;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 );}} }}

:

Http://download.csdn.net/detail/xiaoxiaobian3310903/4502206

Http://download.csdn.net/detail/xiaoxiaobian3310903/4502201

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.