0

我是套接字编程的新手。我正在使用多播套接字通过 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() 方法时卡住了。我在两边都启动了我的移动数据。在服务器端启动热点并从客户端连接到它。

4

2 回答 2

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()

于 2016-04-18T05:52:39.453 回答
-1

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

    byte[] buf = new byte[256];
    packet = new DatagramPacket(buf, buf.length);
    socket.setBroadcast(true);
    socket.receive(packet);
于 2016-04-18T04:40:13.093 回答