#Tcp Server Connection

19 messages · Page 1 of 1 (latest)

regal harbor
#

I wonder how to send a data to rust tcp server

The below is my rust code

use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:80")?;

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                handle_connection(stream);
            }
            Err(e) => { /* connection failed */ }
        }
    }
    Ok(())
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);

    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();


    let status_line = "HTTP/1.1 200 OK";
    let contents = fs::read_to_string("hello.html").unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}

and below is my HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Hello!</title>

    <script>
        function test(){
            console.log("How to send a data to rust server?");
        }
    </script>
</head>
<body>
    <button onclick="test()">test</button>
</body>
</html>

How to send a data to rust server?

latent dune
#

curl?

#

e.g. curl -v 127.0.0.1:80

regal harbor
latent dune
#

Oh right I didn’t see the JS

latent dune
#

e.g. let response = await fetch("/");

regal harbor
latent dune
#

it’s not the same as PHP’s fetch function, no

#

it’s the same as Javascript’s fetch function, if you were to generate the Javascript using PHP

#

because it’s just Javascript

regal harbor
latent dune
#

I doubt an example would help

#

sending data to a Rust server is the same as any other server, there exists plenty of examples of that online

#

but it really depends what format your Rust server is expecting data in

latent dune