【问题标题】:Android UDP doesn't receive in some devicesAndroid UDP 在某些设备中无法接收
【发布时间】:2015-06-18 20:20:53
【问题描述】:

我有一个 UDP 发送和接收,它在我的设备 Samsung Galaxy Ace Plus (S7500) 中有效,但相同的代码在其他设备中无效,例如 Samsung Galaxy S4。我没有任何错误。

发送:

public class SendThread extends Thread {

byte[] receiveData = new byte[1024];
DatagramSocket serverSocket = null;


public SendThread() {
    this.start();
}

public void run() {
    DatagramSocket serverSocket = null;
    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte[1024];

    try {
        serverSocket = new DatagramSocket("MY SOCKET PORT");
        InetAddress IP = InetAddress.getByName("MY IP");
        String send= "I am Android";
        sendData = send.getBytes();
        DatagramPacket send = new DatagramPacket(sendData, sendData.length, IP, "MY SEND PORT");
        serverSocket.send(send);

        serverSocket.close();
    } catch (Exception e) {
    }

}

}

接收:

public class ReceiveThread extends Thread {

byte[] receiveData = new byte[1024];
DatagramSocket serverSocket = null;
boolean isActive = true;

public ReceiveThread() {
    this.start();
}

public void run() {

    DatagramSocket serverSocket = null;
    byte[] receiveData = new byte[1024];

    while (isActive) {
        try {
            serverSocket = new DatagramSocket("MY RECEIVE PORT");

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            String sentence = new String( receivePacket.getData());
            System.out.println("RECEIVED: " + sentence);

            serverSocket.close();

        } catch (Exception e){
        }
    }
}

}

【问题讨论】:

    标签: java android multithreading udp send


    【解决方案1】:

    出现这个问题是因为一些设备因为工厂实现的协议安全性而锁定了数据报接收方。

    您的代码没有错,但您需要将 DatagramSocket 更改为 MulticastSocket。

    为此,您需要执行一些步骤:

    首先,需要添加使用权限:

    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
    

    在 AmdroidManifest.xml 上

    其次,需要创建一个MulticastLock;没有这个 MulticastSocket 就不能正常工作;

    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    multicastLock = wifi.createMulticastLock("multicastLock");
    multicastLock.setReferenceCounted(true);
    

    第三,用MulticastSocket代替DatagramSocket。只有在接收方法上才需要将代码放在下面或类似的地方:

    MulticastSocket ms = new MulticastScoket("Your socket port");
    ms.joinGroup("Your IP");
    

    发送消息不需要任何修改。

    我使用组播 ip 等于 239.255.255.255。尝试多播 ip 的范围,因为错误的 ip 将正确阻止方法流。

    最后,使用MulticastSocket前需要执行MulticastLock.acquire(),使用后执行MulticastLock.release()

    它可以投入服务,并在启动或停止服务时获取或释放MulticastLock。

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多