数据接收上的多播套接字Android错误?

时间:2016-04-09 16:39:55

标签: android network-programming udp broadcast multicastsocket

我是套接字编程的新手。我正在使用多播套接字通过wifi热点网络进行广播。但我在接收方面临问题。 这是我的代码 服务器端

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class SenderService extends Service
{
SenderThread currentSender;

public class SenderThread extends Thread
{

    public void run()
    {
        Log.d("in thread","in service");
        try
        {
            InetAddress group = InetAddress.getByName("224.0.0.3");
            int port=10000;
            DatagramSocket sock=new DatagramSocket();
            sock.setBroadcast(true);
            String msg="hello";
            byte []b3=new byte[1024];
            DatagramPacket packet;
            b3=msg.getBytes();

            while (true)
            {   
                try
                {
                    packet = new DatagramPacket(b3, b3.length,group, port); 
                    sock.send(packet);
                    Log.d("MSG:", "sent");
                } catch (IOException e)
                {
                    Log.d("Send Excp:", e+"");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                finally
                {
                    sock.close();
                }
            }

        } catch (Exception e)
        {

            e.printStackTrace();
        }

    }
}
@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
}

@Override
public IBinder onBind(Intent arg0)
{
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    new SenderThread().start();
    return Service.START_STICKY;
}
}

客户端代码

 import java.io.IOException;
 import java.net.DatagramPacket;
 import java.net.DatagramSocket;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.MulticastSocket;
 import java.net.NetworkInterface;
 import java.util.Enumeration;

 import android.app.Activity;
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.net.wifi.WifiManager;
 import android.net.wifi.WifiManager.MulticastLock;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Handler;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.Toast;

 public class ReceiverActivity extends Activity
 {
    Button b;
    Handler h;
    class MyRTh extends Thread
    {
        InetAddress group=null ;
        WifiManager wifi =    (WifiManager)getSystemService(Context.WIFI_SERVICE);
        MulticastLock lock = wifi.createMulticastLock("HelloAndroid");

        public void run()
        {
            try
            {
                lock.acquire();
            }
            catch (Exception e) {
                // TODO: handle exception
                Log.d("lock",e+"");
            }
            try
            {
                final MulticastSocket sock=new MulticastSocket(10000);
                group= InetAddress.getByName("224.0.0.3");
                //sock.setSoTimeout(15000);
                try
                {
                    sock.joinGroup(group);
                }
                catch(Exception e)
                {
                    Log.d("join",""+e.toString());
                }
                while(true)
                {
                try
                {
                    Log.d("in try","l4");
                    byte[] data = new byte[1024]; 

                    // TODO Auto-generated method stub
                    DatagramPacket packet = new DatagramPacket(data, data.length);
                    Log.d("in run","l4");
                    try {
                        sock.receive(packet);
                        String s = new String(packet.getData());
                        Log.e("MSG:", "Received");
                        Log.d("msg",s);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Log.d("err",e.toString());
                    }
                }
                catch (Exception e)
                {
                    Log.d("Excp", e.toString()+"");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }
                }catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_receiver);
    Toast.makeText(getApplicationContext(), "Receiving", Toast.LENGTH_SHORT).show();
    Log.d("1","l1");

    b=(Button)findViewById(R.id.buttonr);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0)
        {
            MyRTh th=new MyRTh();
            th.start();
        }
    });
}

}

我的问题是我的客户端代码在转到socket.receive()方法时卡住了。我在双方都开始了我的移动数据。在服务器端启动Hotspot并从客户端连接到它。

2 个答案:

答案 0 :(得分:0)

  

我的问题是我的客户端代码在转到socket.receive()方法时卡住了

阻止

InetAddress group = InetAddress.getByName("224.0.0.3");

问题出在这里。 224.0.0.0到224.0.0.255范围内的多播地址保留用于低级多播支持操作。使用224.0.1.0到239.255.255.255范围内的地址,但也请参阅RFC 2365。

sock.setBroadcast(true);

不必要的。去掉。你没有广播,你是多播。

byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();

以后重新分配两行时,您不需要初始化b3

finally
{
    sock.close();
}

您正在关闭while (true)循环内的套接字。因此,它会发送一个多播,然后在“'套接字关闭”的情况下退出。例外情况,您尚未在此处报告。去掉。

String s = new String(packet.getData());

那应该是new String(packet.getData(), packet.getOffset(), packet.getLength()

答案 1 :(得分:-1)

尝试设置此启用socket.setBroadcast(true);

    byte[] buf = new byte[256];
    packet = new DatagramPacket(buf, buf.length);
    socket.setBroadcast(true);
    socket.receive(packet);