简体   繁体   中英

Receive on UDP socket and send reply

I am working on a client/server project, the client being Android and the server being C#.

What I am trying to do is the Android app listens on a UDP socket and the C# server sends a message on that port. Android will then receive the message from the reply, and send back a response.

This is the code I have:

public void run()
    {
        Log.d(TAG, "Heartbeat manager thread starting");
        try
        {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            DatagramSocket socket = new DatagramSocket(HEARTBEAT_PORT);

            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            while (!cancelThread)
            {
                socket.receive(packet);

                final String xml = new String(packet.getData(), 0, packet.getLength());

                Log.v(TAG, xml);

                XmlSettings xmlSettings = new XmlSettings();
                xmlSettings.setIndent(true);
                XmlWriter writer = new XmlWriter(xmlSettings);

                writer.writeStartDocument();
                writer.writeStartElement("HeartbeatManager");
                writer.writeElementString("Command", Defines.ServerCommands.HeartbeatResponse.toString());
                writer.writeEndElement();

                buffer = writer.returnXmlOutput().getBytes();

                DatagramPacket replyPacket = new DatagramPacket(buffer, buffer.length);
                socket.send(replyPacket);
            }
        }
        catch (SocketException ex)
        {
            Log.e(TAG, "Socket Exception Occurred: " + ex.toString());
        }
        catch (IOException ex)
        {
            Log.e(TAG, "IOException Occurred: " + ex.toString());
        }

At the moment it throws an exception when I do the socket.send stating that the destination address is null.

Thanks for any help you can provide.

You must set the destination address in the DatagramPacket before sending it.

The constructor you're using (without the address) is just for receiving, not for sending.

In UDP protocol, destination is set in the packet because there is not a connection (like TCP) So in your code you are telling the socket, which has no concecpt of destination to send a packet without destination, so it'll throw and exception.

InetSocketAddress address = InetSocketAddress("www.google.com", 8080);
DatagramPacket replyPacket = new DatagramPacket(buffer, buffer.length, address); 
socket.send(replyPacket);

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