Android UDP套接字无法接收

时间:2011-12-18 18:02:55

标签: android udp

我写了一个简单的服务器程序,试图在Android手机上接收UDP数据报包。有一个客户端程序发送数据报包。但是,socket.receive()仅在客户端在将数据包发送到localhost ip的同一手机上运行时才有效。数据报套接字似乎无法接收从其他手机发送的数据包。

以下是服务器的代码

public class wateverActivity extends Activity {

static DatagramSocket socket;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try{
        socket = new DatagramSocket(11111);
        byte[] receiveData = new byte[512];

        DatagramPacket datagram = new DatagramPacket(receiveData, 0, receiveData.length,null, 0);


        try{
            socket.receive(datagram);
            String data = new String(datagram.getData());
            Toast.makeText(getBaseContext(),"datagram received = " + data,Toast.LENGTH_LONG).show();
        }

        catch(IOException e)
        {
            Toast.makeText(getBaseContext(),"I/O Exception",Toast.LENGTH_LONG).show();
        }
    }
    catch(SocketException e)
    {
        Toast.makeText(getBaseContext(),"Socket Exception",Toast.LENGTH_LONG).show();
    }

    socket.close();
    Toast.makeText(getBaseContext(),"Socket close",Toast.LENGTH_LONG).show();


}   


}

以下是客户端代码

public class UdpClient extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    runUdpClient();
    finish();
}
private static final int UDP_SERVER_PORT = 11111;
private void runUdpClient()  {
    String udpMsg = "hello world from UDP client " + UDP_SERVER_PORT;
    DatagramSocket ds = null;
    try {
        ds = new DatagramSocket();
        InetAddress serverAddr = InetAddress.getByName("127.0.0.1");
        DatagramPacket dp;
        dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
        ds.send(dp);
    } catch (SocketException e) {
        e.printStackTrace();
    }catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ds != null) {
            ds.close();
        }
    }
}
}

对于这两个代码我都在清单文件下包含了互联网权限。但是,服务器仍然无法接收任何数据报包。

0 个答案:

没有答案