Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android socket通信建立

android socket通信建立

編輯:關於Android編程

最近做了一個類似google remote的應用,主要功能是手機端通過網絡發出按鍵,接收端接收並處理其事件;
這裡理所當然就想到socket通信。而要建立連接實現要知道接收端的IP地址,參考網咯最終實現;以下是發送端和接收端的實現代碼。

接收端:

  	protected static final int SendPort = 8600;
	  protected static final int ReceivePort = 8601;
  	private MulticastSocket socket;
	  private InetAddress address;
	  private DatagramPacket packet;
	
		socket = new MulticastSocket(ReceivePort);
	  address = InetAddress.getByName("224.0.0.1");
		socket.joinGroup(address);
			
			
		private Runnable mSendRunnable = new Runnable() {  
        public void run() {
    		//發送數據包,尋找接收端
    		byte[] buf = "SMART IR".getBytes();
    		packet = new DatagramPacket(buf, buf.length, address, SendPort);
    		try {
    			socket.send(packet);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }
	};
	

接收端:

    
public class IRReceiveSetupConnectSocket { 
	protected static final String TAG = "MultiSocketA";
	protected static final int SendPort = 8601;
	protected static final int ReceivePort = 8600;

	private MulticastSocket socket; 
	private InetAddress address;
	private boolean mReceiveMultiSocket = true;
	private int ipaddr;
	public  IRReceiveSetupConnectSocket(int ip) throws IOException{
		ipaddr = ip;
		socket = new MulticastSocket(ReceivePort);
		address = InetAddress.getByName("224.0.0.1");
		socket.joinGroup(address);	
		
		new Thread(run).start();  
		
	}
	
// 此thread會一直poll multisovket的信息,只要有接受到信息,就將自己ip地址廣播出去;發送端可以以此地址發送key(其它線程的socket)
	Runnable run = new Runnable() {  
        @Override  
        public void run() {
        	while(mReceiveMultiSocket)
        	{
        		byte[] rev = new byte[128];
        		DatagramPacket packet = new DatagramPacket(rev, rev.length);
        		try {
        			Log.d("yanxi", "MultiSocket Waitting.......");
        			
        			//receive connect requst,and send ipaddr to request host
					socket.receive(packet);
					Log.d("yanxi", "MultiSocket received........"+ new String(packet.getData()).trim());        		

					//send ipaddr to request host
					byte[] buf = (""+ipaddr).getBytes();
					packet = new DatagramPacket(buf, buf.length, address, SendPort);
					socket.send(packet);
					Log.d("yanxi", "MultiSocket send........"+ ipaddr);        		
					//mReceiveMultiSocket = false;
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}     
        }  
    }; 

	          
}

通過以上實現發送端就能得到接收端的IP,從而為後面的發送IR Code做基礎


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved