从ANDROID 2.2发送UDP包(HTC欲望)

时间:2011-02-18 14:35:40

标签: java android sockets sdk udp

我有一个局域网,我想从我的机器人(htc欲望)发送一条更新消息到我的电脑。他们之间有一个Wlan路由器。问题是,UPD消息永远不会到达PC。

Android上的代码。:

package org.example.androidapp;

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

public class UDPClientAnd {

    public void sendUDPMessage(int port) throws java.io.IOException {
        DatagramSocket socket = new DatagramSocket();
        InetAddress serverIP = InetAddress.getByName("192.168.1.110");
        byte[] outData = ("Ping").getBytes();
        DatagramPacket out = new DatagramPacket(outData,outData.length, serverIP,50005);
        socket.send(out);
        socket.close();
    }

}

我在展位两侧选择一个高端口。

Android上的权限是:

uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" 

服务器端PC只是一个简单的接收程序:

package org.example.androidapp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UPDServerAnd implements Runnable{
public void run(){
byte[] inData = new byte[48];
byte[] outData = new byte[48];
String message;
DatagramSocket socket;
try {
    socket = new DatagramSocket(50005);
    while (true) {
        DatagramPacket in = new DatagramPacket(inData,inData.length);
        socket.receive(in);
        InetAddress senderIP = in.getAddress();
        int senderPort = in.getPort();
        message=new String(in.getData(),0,in.getLength());
        System.out.println("Got "+message+" from "+senderIP+","+senderPort);
        outData = "Pong".getBytes();
        DatagramPacket out = new DatagramPacket(outData,outData.length, senderIP,senderPort);
        socket.send(out);
        }
} catch (SocketException e) {
    e.printStackTrace();
} 
 catch (IOException e) {
    e.printStackTrace();
}

}

}

那么为什么没有来自android的UDP Package可见?甚至Wireshark也只显示了一些ARP包。 Plz帮助:)

1 个答案:

答案 0 :(得分:1)

我遇到了一个非常类似的问题。我的解决方案是添加:

uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"

Manifest.xml文件。然后我禁用了所有Windows firewall并且它有效。我能够从String向PC发送Droid