안 드 로 이 드 는 UDP 패키지 와 자바 프로그램 을 보 내 받 습 니 다.

다음으로 이동:http://blog.sina.com.cn/s/blog_6c0a8fbb0100s3k5.html
내 가 참고 한 블 로그 에서 설명 을 잊 어 버 리 면 Manifest 에 네트워크 권한 을 추가 해 야 합 니 다 (< uses - permission android: name = "android. permission. INTERNET" > < / uses - permission >)
android 엔 드 코드:
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() {

		@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();
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    
}

자바 엔 드 코드:
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

좋은 웹페이지 즐겨찾기