java – 如何在Android中使用UDP套接字?

前端之家收集整理的这篇文章主要介绍了java – 如何在Android中使用UDP套接字?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在 Android中使用UDP套接字,这里我从Android模拟器发送我的字符串,并通过我的Java程序在PC上接收到,但是我的Java程序没有收到任何东西,尽管我使用Java程序作为客户端和服务器我做了两个不同的Java程序)它的工作.

这是我的Android主要活动:

public class First extends Activity {
Button b;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Thread t = new Thread(new Second());
            t.start();
        }
    });

这是我android中的第二课

public class Second implements Runnable {
Second()
{
    run();
}
public void run() {
    // TODO Auto-generated method stub
    try {

        String messageStr = "Hello Android!";
        int server_port = 9876;
        DatagramSocket s = new DatagramSocket();
        InetAddress local = InetAddress.getByName("127.0.0.1");
        int msg_length = messageStr.length();
        byte[] message = messageStr.getBytes();
        DatagramPacket p = new DatagramPacket(message,msg_length,local,server_port);
        s.send(p);
    } catch (Exception e) {

    }
}
}

这是我PC上的Java代码

public static void main(String args[]) throws Exception
    {
            DatagramSocket serverSocket = new DatagramSocket(9876);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while(true)
            {
                    DatagramPacket receivePacket = new     DatagramPacket(receiveData,receiveData.length);
                    serverSocket.receive(receivePacket);
                    String sentence = new String(receivePacket.getData(),receivePacket.getLength());
                    InetAddress IPAddress = receivePacket.getAddress();
                    int port = receivePacket.getPort();
                    System.out.println("MESSAGE RECEIVED  "+sentence+"  "+IPAddress+"         "+port);
            }
     }

解决方法

在Android仿真(和Android设备)上,127.0.0.1表示Android仿真机,而不是主机PC.您可以在 10.0.2.2访问您的主机
原文链接:https://www.f2er.com/android/123494.html

猜你在找的Android相关文章