【问题标题】:Creating a UDP Connection on Android Emulator在 Android 模拟器上创建 UDP 连接
【发布时间】:2017-06-17 17:30:59
【问题描述】:

我正在尝试使用 Android Studio 及其模拟器在给定端口上创建一个简单的 UDP 连接。我能够在 Eclipse 的线程中运行的客户端/服务器上完成这项工作。

但是,当将代码移植到 android 时,打开的端口是 TCP。

下面是安卓代码:

@Override
    public void run() {
        // Perform our network ops in this loop, anything blocking really...

        try {
            Log.d(TAG, "UDP Connecting to " + HOST + " on port " + PORT);
            datagramSocket = new DatagramSocket();

            String host = "localhost";
            InetAddress address = InetAddress.getByName(host);

            byte[] message = "UDP is da best".getBytes();
            DatagramPacket packet = new DatagramPacket(message, message.length, address, PORT);

            datagramSocket.send(packet);

            byte[] buffer = new byte[65536];
            DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

            while (true) {
                datagramSocket.receive(incoming);
                byte[] data = incoming.getData();
                String s = new String(data, 0, incoming.getLength());

                Log.d(TAG, "Client: " + incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " - " + s);

                Thread.sleep(500);

                DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , PORT);
                datagramSocket.send(dp);
            }
        } catch (Exception e) {
            Log.d(TAG, e.toString());
        }

    }

这段代码几乎取自here

这是正在创建为 TCP 的端口的图片:

【问题讨论】:

  • 我发现 5555 端口已经被 android 使用了,所以我搬到了 9876 仍然没有结果

标签: java android sockets udp


【解决方案1】:

问题通过首先更改端口解决,因为 5555 正在使用中,而 127.0.0.1 也不是要使用的 ip,使用 10.0.2.2 让我连接,一切顺利

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2011-08-30
    • 2011-12-30
    • 2018-02-12
    • 1970-01-01
    相关资源
    最近更新 更多