【Android】一个通过组播实现的局域网服务器搜索功能

服务器端代码:

package com.isunhui.multicast;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;

public class Main {
	public static void main(String[] args){
		try{
			MulticastSocket ms = new  MulticastSocket(10000);//生成套接字并绑定端口
			InetAddress group = InetAddress.getByName("224.0.0.1");//设定多播IP
			ms.setNetworkInterface(NetworkInterface.getByInetAddress(group.getLocalHost()));
			ms.joinGroup(group);//接受者加入多播组,需要和发送者在同一组
			byte[] buf = new byte[100];
			DatagramPacket packet = new DatagramPacket(buf , buf.length);//创建接收报文,以接收通过广播传递过来的
			while(true){
				ms.receive(packet);//接收报文,程序停滞等待直到接收到报文
				System.out.println("receive:"+new String(packet.getData()));
				System.out.println("from "+packet.getAddress().getHostAddress());

				DatagramSocket ds = new DatagramSocket(); 
				byte[] buf2 = "server address".getBytes("utf-8");
				DatagramPacket packet2=new DatagramPacket(buf2,buf2.length,packet.getAddress(),10001);
				ds.send(packet2);//发送报文
				ds.close();
			}
		}catch(Exception e){
			System.out.println(e.toString());
		}
	}
}

手机端代码:

package com.isunhui.multicast;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
	private Button send;
    private TextView serverIP;
    private TextView localIP;
    private ArrayList<InetAddress> ipList;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        serverIP = (TextView)findViewById(R.id.serverIP);
        localIP = (TextView)findViewById(R.id.localIP);
        send = (Button)findViewById(R.id.send);
        ipList = new ArrayList<InetAddress>();
        handler = new Handler();
        
        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())
                    {
                        ipList.add(inetAddress);
                    }
                }
            }
        }
        catch (Exception e)
        {
            Log.e("getIP", e.toString());
        }
        localIP.setText("本地IP:"+ipList.get(1).getHostAddress().toString());

        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try{
                    MulticastSocket msSocket = new MulticastSocket();//生成套接字并绑定30001端口
                    InetAddress group=InetAddress.getByName("224.0.0.1");//设定多播IP
                    byte[] buff = "search server".getBytes("utf-8");//设定多播报文的数据
                    msSocket.joinGroup(group);//加入多播组,发送方和接受方处于同一组时,接收方可抓取多播报文信息
                    msSocket.setTimeToLive(4);//设定TTL
//设定UDP报文(内容,内容长度,多播组,端口)
                    DatagramPacket packet = new DatagramPacket(buff,buff.length,group,10000);
                    msSocket.send(packet);//发送报文
                    msSocket.close();//关闭套接字
                    
                    DatagramSocket ds = new DatagramSocket(10001);
                    byte[] buf2 = new byte[100];
                    DatagramPacket packet2 = new DatagramPacket(buf2,buf2.length);
                    ds.receive(packet2);
                    ds.close();
                    final String serverIP_str=packet2.getAddress().getHostAddress();
                    handler.post(new Runnable(){
						@Override
						public void run() {
							// TODO Auto-generated method stub
							serverIP.setText("服务器IP:"+serverIP_str);
						}                    
                    });
                }catch (Exception e){
                    Log.e("sendMulticast",e.toString());
                }
            }
        };

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(runnable).start();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

此条目发表在Android技术分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注