【问题标题】:Udp client working in java but not in androidudp客户端在java中工作但不在android中
【发布时间】:2016-11-12 06:46:33
【问题描述】:

我已经在 netbeans 中测试了该程序,它运行良好,但在 android 中无法运行。它没有接收任何数据并在这一行被阻止,但 netbeans 中的相同代码能够接收数据。执行时没有抛出错误或异常。感谢您的任何建议。

    import java.net.InetSocketAddress;
        import java.nio.ByteBuffer;
        import java.nio.ByteOrder;
        import java.nio.channels.DatagramChannel;

        public class StarterThread implements Runnable {

            Thread t;
            DatagramChannel channel;


            StarterThread() {
                t = new Thread(this, "Starter Thread");
                System.out.println("Starter Thread : " + t);
                t.start();
            }

            public void run() {
                try {
                    channel = DatagramChannel.open();
                    channel.connect(new InetSocketAddress("192.168.43.62", 49191));
                    String newData = "START\r\n";
                    ByteBuffer buf = ByteBuffer.allocate(190);
                    buf.order(ByteOrder.LITTLE_ENDIAN);

                    buf.clear();
                    buf.put(newData.getBytes());
                    buf.flip();
                    channel.write(buf);
                    int i = 0;
                    while (true) {
                        Log.i("Info", "In while loop");
                        buf.clear();
                        Log.i("log i", "" + i);
                        InetSocketAddress client = (InetSocketAddress) channel.receive(buf);
                        buf.flip();
                        Log.i("TimeStamp", " " + JIHelper.getUnsignedInt(buf.getInt()));
                        System.out.println(new String(buf.array(), "UTF-8"));
                        i++;
                        Log.i("log i", "" + i);
                        if (i % 10 == 0) {
                            newData = "KEEP-ALIVE\r\n";
                            Log.i("Message sent", "KEEP-ALIVE SENT");
                            buf.clear();
                            buf.put(newData.getBytes());
                            buf.flip();
                            channel.write(buf);
                            if (i == 100)
                                i = 0;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        public class DisplayActivity extends AppCompatActivity {
         public void sendStartPacket(View view) {
        new StarterThread();
        }
}

【问题讨论】:

    标签: java android netbeans network-programming android-networking


    【解决方案1】:

    如果您使用 Android >= 5.0,则 DatagramChannel.receive() 不起作用。您需要改用 DatagramChannel.read()。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 2013-10-20
    • 2023-03-06
    相关资源
    最近更新 更多