如何通过UDP客户端接收文本字符串

时间:2012-09-25 15:28:19

标签: android udp

我正在创建一个非常简单的应用程序,我在我的PC上从java程序发送一个文本字符串,我试图从模拟器中的Android应用程序接收相同的字符串。

这是我的活动(服​​务器):

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_appstart);
    tv = (TextView) findViewById(R.id.textView1);
    try {
        DatagramSocket clientsocket = new DatagramSocket(9876);
        byte[] receivedata = new byte[1024];
        DatagramPacket recv_packet = new                   DatagramPacket(receivedata, receivedata.length);
        Log.d("UDP", "S: Receiving 1 sec...");
        clientsocket.receive(recv_packet);
        String rec_str = new String(recv_packet.getData());
        tv.setText(rec_str);
        Log.d(" Received String ", rec_str);
        InetAddress ipaddress = recv_packet.getAddress();
        int port = recv_packet.getPort();
        Log.d("IPAddress : ", ipaddress.toString());
        Log.d(" Port : ", Integer.toString(port));                                   clientsocket.close();
    } catch (Exception e) {
        Log.e("UDP", "S: Error", e);
    }
}

这是我的PC客户端java代码:

  public static void main(String args[]) throws Exception
    {
            while(true)
    {           
    BufferedReader inFromUser = new BufferedReader(new       InputStreamReader(System.in));
            DatagramSocket clientSocket = new DatagramSocket();
            InetAddress IPAddress = InetAddress.getByName("127.0.0.1");
    System.out.println(IPAddress.getHostName());
            byte[] sendData = new byte[1024];
            byte[] receiveData = new byte[1024];
            String sentence = inFromUser.readLine();
            sendData = sentence.getBytes();
            DatagramPacket sendPacket = new    DatagramPacket(sendData,sendData.length,IPAddress,9876);
            clientSocket.send(sendPacket);
    System.out.println(sendPacket.getPort());
            clientSocket.close();
    }       
   }

然而,该应用程序没有收到任何内容,但在Android应用程序中的onReceive()函数上引发异常....

有人知道为什么吗?

2 个答案:

答案 0 :(得分:0)

你得到android.os.NetworkOnMainThreadException,因为你在主线程上运行网络方法,这将使你的应用程序无法响应。尝试将它放入一个单独的线程或...在这种情况下,也许是您的Activity可以绑定到的服务。 (有关示例,请参阅How to fix android.os.NetworkOnMainThreadException?

如果(不推荐)您只需要测试您的UDP服务,您可以将API要求设置为7或更低或在主线程策略上禁用网络,您将不会收到异常。但是,您的应用将高度反应迟钝。

答案 1 :(得分:0)

试试这个POC。它发送和侦听数据包。 将侦听器拆分为另一个线程

package a.first;

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


public class Serv {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

        Listner listner = new Listner();
        Thread thread = new Thread(listner);
        thread.start();


        String messageStr = "Hello msg1";
        int server_port = 2425;
        DatagramSocket s = new DatagramSocket();
        InetAddress local = InetAddress.getByName("172.20.88.223");
        int msg_length = messageStr.length();
        byte[] message = messageStr.getBytes();
        DatagramPacket p = new DatagramPacket(message, msg_length, local,
                server_port);
        System.out.println("about to send msg1");
        s.send(p);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
        messageStr = "Hello msg2";
        msg_length = messageStr.length();
        message = messageStr.getBytes();
        p = new DatagramPacket(message, msg_length, local,
                server_port);
        System.out.println("about to send msg2");
        s.send(p);
}


}
   class Listner implements Runnable
    { 
            @Override
            public void run() {
        String text = null;
        while(true){
            text = null;    
        int server_port = 2425;
        byte[] message = new byte[1500];
        DatagramPacket p = new DatagramPacket(message, message.length);
        DatagramSocket s = null;
        try{
           s = new DatagramSocket(server_port);
        }catch (SocketException e) {
            e.printStackTrace();
            System.out.println("Socket excep");
        }
        try {
        s.receive(p);
       }catch (IOException e) {
            e.printStackTrace();
                System.out.println("IO EXcept");
            }
        text = new String(message, 0, p.getLength());
        System.out.println("message = "+text);
        s.close();

    }
}

}