首页 > 移动平台 > 详细

android socket通信建立

时间:2014-01-21 09:29:36      阅读:477      评论:0      收藏:0      [点我收藏+]
  最近做了一个类似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做基础


android socket通信建立

原文:http://blog.csdn.net/cuityanxi/article/details/18267249

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!