Android listening port receives messages

Other articles

Below is another article of mine, which is about sending data on the computer. With this article, LAN communication between the computer and the mobile phone can be achieved. Just copy and paste it, it's very easy to use.
Click to connect.
In addition, if you don’t know your mobile phone IP, you can also obtain it through the following article. This article is for LAN IP and is limited to LAN testing.
Click to connect

listening port

We can create a DatagramSocket object for receiving UDP messages on a specified port.

DatagramSocket is a class used for UDP communication in Java, which represents a datagram socket. Through the DatagramSocket object, we can send and receive UDP datagrams.

The sample code is as follows:

val udpSocket = DatagramSocket(port)

The port variable is the specified port number, used to specify the port bound to the UDP socket. The created udpSocket object will listen on the target port number to receive UDP messages from other nodes.

receive messages

Once a DatagramSocket object is created, you can use the object's receive method to receive UDP messages and store the received data in a DatagramPacket object, and then parse the DatagramPacket object to obtain the actual message content.
The sample code is as follows:

val buffer = ByteArray(1024)
val packet = DatagramPacket(buffer, buffer.size)
udpSocket.receive(packet)

After receiving the message, you can perform corresponding processing operations, such as updating the UI, etc.

Create new thread

In Android development, the main thread (also called the UI thread) is responsible for processing user interface updates and responding to user interaction events, including processing user input, rendering the interface and other operations. If time-consuming operations are performed in the main thread, such as network requests, file reading and writing, etc., it will cause the interface to freeze, become unresponsive, or have ANR errors.

To avoid this situation, you need to use Thread to create a new thread when performing network data reception operations. Execute time-consuming operations in a new thread to maintain the responsiveness of the main thread. In this way, the main thread can still continue to process user interface updates and events without being stuck or unresponsive due to being blocked on receiving message operations.

To start a new thread, first create a Thread object and pass in a Runnable object as a parameter. Runnable objects define the operations to be performed by the thread.
The sample code is as follows:

val receiveThread = Thread(Runnable {
    
    
})

In a thread, we can obtain the currently executing thread object through the Thread.currentThread() method.
You can check whether the current thread is interrupted through the isInterrupted() method of the thread object. If the thread is interrupted, the isInterrupted() method will return true, otherwise it will return false.
In this way, we can continuously receive data through a loop in the thread.
The sample code is as follows:

while (!Thread.currentThread().isInterrupted) {
    
    
}

The loop condition indicates that the code within the loop body is executed when the current thread is not interrupted. In this way, the program performs persistent tasks in the background thread and does not exit the loop until the thread is interrupted or the task is completed.

Of course, to end the loop inside the loop body, just execute the Thread.currentThread().interrupt() method, which will interrupt the current thread. Then the isInterrupted() method will return true, the loop condition will no longer be met, and the loop will exit. This can be used to stop the thread's execution and terminate the loop.

Finally we get the following code:

val receiveThread = Thread(Runnable {
    
    
    val udpSocket = DatagramSocket(port)
    val buffer = ByteArray(1024)
    val packet = DatagramPacket(buffer, buffer.size)

    while (!Thread.currentThread().isInterrupted) {
    
    
        try {
    
    
            udpSocket.receive(packet)
            val receivedData: String = String(packet.data, 0, packet.length)
            runOnUiThread {
    
    
                updateReceivedMessage(receivedData)
            }
        } catch (e: Exception) {
    
    
            e.printStackTrace()
        }
    }
    udpSocket.disconnect()
    udpSocket.close()
})

In the run method of the Runnable object, we create a DatagramSocket object and specify the port number to listen on. Then we created a byte array buffer and a DatagramPacket object packet for receiving UDP data.
In the loop, we use the udpSocket.receive(packet) method to receive data. Once data arrives, the receive method blocks until the data arrives or an exception occurs. When the data arrives, use the packet object to extract the string from the received data, and call the runOnUiThread method to update the text content of the receivedMessageTextView on the interface in the UI thread to display the received message.

After the loop ends, remember to close the udpSocket connection.

Complete code

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import java.net.DatagramPacket
import java.net.DatagramSocket

class MainActivity : AppCompatActivity() {
    
    
    private val port = 8888

    private lateinit var receivedMessageTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        receivedMessageTextView = findViewById(R.id.tv_received_message)

        val receiveThread = Thread(Runnable {
    
    
            val udpSocket = DatagramSocket(port)
            val buffer = ByteArray(1024)
            val packet = DatagramPacket(buffer, buffer.size)

            while (!Thread.currentThread().isInterrupted) {
    
    
                try {
    
    
                    udpSocket.receive(packet)
                    val receivedData: String = String(packet.data, 0, packet.length)
                    runOnUiThread {
    
    
                        updateReceivedMessage(receivedData)
                    }
                } catch (e: Exception) {
    
    
                    e.printStackTrace()
                }
            }
            udpSocket.disconnect()
            udpSocket.close()
        })

        receiveThread.start()
    }

    private fun updateReceivedMessage(message: String) {
    
    
        receivedMessageTextView.text = message
    }
}

Guess you like

Origin blog.csdn.net/weixin_44499065/article/details/132316758