Android - 无法发送DatagramPacket

时间:2014-03-31 21:41:00

标签: java android multithreading udp

我正在构建一个程序,它将在两个Android设备之间发送/接收数据。 首先,我创建了一个客户端线程来发送数据

public void run() {
    try {   

        //Create the datagram packet
        byte[] buffer = message.getBytes();
        InetAddress addr = InetAddress.getByName(address);
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, addr, 5555);


        //Create Datagram Socket

        DatagramSocket socket =  new DatagramSocket();
        socket.setBroadcast(broadcast);

        // send the packet
        socket.send(packet); // i think that the problem was here



    } catch (Exception e) {
        e.printStackTrace();
        Log.i("CTHREAD", "erreur");
    }

在服务器线程上,我想收到这个数据包,所以我打开了一个datagramsocket来接收10个数据包。

 public void run() {
            try {

                  serverIP = getLocalIpAddress();  
                  Log.v("addr", serverIP);        
                  serverSocket = new ServerSocket(5001); 
                  Log.v("socket", "created");


                  while(socketOk) { //boucle infini                  
                         Socket client = serverSocket.accept();
                        // Log.v("client", "received");
                         try {

                            DatagramSocket socket = new DatagramSocket(5556);
                            byte[] buf = new byte[1024]; //buffer
                            DatagramPacket packet = new DatagramPacket(buf, buf.length); 
                            socket.receive(packet);
                            byte[] result = new byte[packet.getLength()];
                            System.arraycopy(packet.getData(), 0, result, 0, packet.getLength());
                            String msg = new String(result);
                            updateGui(msg, packet.getAddress());


                         } catch (Exception e) {
                             socketOk =false;
                             Log.v("ServerThread", "SocketOk =false");

                         }
                     }
                  } 
                catch (Exception e) {}
        }
}       

当我想发送消息时,我会收到一些警告,因此程序无法运行ClientThread。

at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:506)
at libcore.io.IoBridge.sendto(IoBridge.java:475)
at java.net.DatagramSocket.send(DatagramSocket.java:284)
Caused by: libcore.io.ErrnoException: sendto failed: EACCES (Permission denied)

的Manifest.xml:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>  
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>  
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />  

那么,问题是怎么回事?我怎么能解决它?

1 个答案:

答案 0 :(得分:0)

您正在发送到5555端口但是您正在通过5556端口接收。

最好让服务器的DatagramSocket在整个过程中保持打开状态。