简体   繁体   中英

Creating a UDP Connection on Android Emulator

I'm trying to create a simple UDP connection on a given port with Android Studio and their emulator. I was able to make this work with a client/server both running in threads with eclipse.

However, when porting the code into android the port that is opened is TCP.

Below is the android code:

@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());
        }

    }

This code is pretty much taken from here

Here is a picture of the ports being created as TCP:

使用第一个更改端口解决问题因为5555正在使用而127.0.0.1也不是要使用的ip,使用10.0.2.2让我连接并解决所有问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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