How do I detect a tcp connection from Android off?

Hi folks, I'm new to Rust, I'm writing a very simple demo, and right now it looks like this:

fn handle_connection(mut stream: TcpStream) {
    let mut packet_size_buffer = vec![0; 4];
    loop {
        match stream.read(&mut packet_size_buffer) {
            Ok(size) => {
                println!("packet size: {}", &packet_size_buffer[0]);
            }
            Err(e) => {
                println!("Error reading packet size: {}", e);
                break;
            }
        }
    }
}

fn main() {
    let listener = TcpListener::bind("0.0.0.0:7878")
        .unwrap();
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                println!("New connection: {}", stream.peer_addr().unwrap());
                thread::spawn(move || {
                    handle_connection(stream);
                });
            }
            Err(e) => {
                println!("Error: {}", e);
            }
        }
    }
}

I have written some code on Android:

    fun connect() {
        viewModelScope.launch(Dispatchers.IO) {
            _socket = Socket("192.168.2.4", 7878)
        }
    }
    fun send() {
        viewModelScope.launch(Dispatchers.IO) {
            val packetSize:Byte = 4
            val packet = byteArrayOf(packetSize)
            _socket?.getOutputStream()?.write(packet)
        }
    }

I can read packets normally, but when I remove my application from the background, my rust console starts an infinite loop, printing the last packet size, which is 4 instead of 0. This makes me feel a bit strange so I can't properly determine the packet size and close the TCP connection.

But I can't detect and send a packet with packet size 0 if the app is forcibly closed from the background, so how should I detect that the TCP connection is closed in this case?

Why are you printing packet_size_buffer[0] instead of the size which is the length of bytes been read from the socket?

it makes sense... I'm stupid..