简体   繁体   English

Android和UDP数据包的奇怪行为

[英]Strange behavior with android and UDP packets

I made a simple app in android studio to send UDP packets, so when I click a button it calls a function to check which type of component called that function and sends different packet's data respectively. 我在android studio中创建了一个简单的应用程序来发送UDP数据包,因此当我单击一个按钮时,它会调用一个函数来检查哪个类型的组件称为该函数,并分别发送不同的数据包数据。 Here is the function which sends the packet: 这是发送数据包的函数:

    public void sendPacket(View v) {
    if (v instanceof Button)
        buffer = ((Button) v).getHint().toString().getBytes();
    else if (v instanceof EditText)
        buffer = ((EditText) v).getText().toString().getBytes();
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, ip, port);
            try {
                SelectionActivity.datagramSocket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}

Here is the listener in the main function which calls the sendPacket() function: 这是main函数中的侦听器,它调用sendPacket()函数:

        btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (<some checks>)
                sendPacket(txt.findViewById(R.id.txt));
            sendPacket(btn.findViewById(R.id.btn));
        }
    });

The problem is that it randomly sends one data and/or the other even if it change . 问题是它随机发送一个数据和/或另一个数据, 即使它发生了变化

For example: 例如:

1) 1)

buffer = 0x01 buffer = 0x01

send 0x01 发送0x01

buffer = 0x02 buffer = 0x02

send 0x02 发送0x02

2) 2)

buffer = 0x01 buffer = 0x01

send 0x01 发送0x01

buffer = 0x02 buffer = 0x02

send 0x01 发送0x01

WTF?! WTF?

通过使用thread.join()解决,因为它需要在使用更新的缓冲区发送新数据包之前等待线程完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM