~starkingdoms/starkingdoms

ref: 1dfcf5efd599f41a169be5c252a3433dd7a67e63 starkingdoms/crates/unified/src/server/management.rs -rw-r--r-- 1.1 KiB
1dfcf5ef — core netcode,thrust: replicate thrusters again 5 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener};

use crate::shared::net::ManagementInfo;

pub fn spawn_management_server(bind: SocketAddr, info: ManagementInfo) {
    let listener = TcpListener::bind(bind).expect("failed to bind management TCP socket");
    let body = serde_json::to_string(&info).expect("failed to serialize management info");

    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(mut stream) = stream else { continue };
            let body = body.clone();
            std::thread::spawn(move || {
                let mut buf = [0u8; 1024];
                let _ = stream.read(&mut buf);

                let response = format!(
                    "HTTP/1.1 200 OK\r\n\
                     Content-Type: application/json\r\n\
                     Access-Control-Allow-Origin: *\r\n\
                     Content-Length: {}\r\n\
                     Connection: close\r\n\
                     \r\n\
                     {body}",
                    body.len(),
                );
                let _ = stream.write_all(response.as_bytes());
            });
        }
    });
}