send a json message to a tcp server in rust

To send a JSON message to a TCP server in Rust, you first need to establish a TCP connection with the server. You can use the TcpStream type from the std::net module to create a TCP connection:

main.rs
use std::io::{Read, Write};
use std::net::TcpStream;

fn main() -> std::io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:8080")?;

    // send JSON message
    let message = r#"{ "name": "John Doe", "age": 42 }"#;
    stream.write(message.as_bytes())?;

    // read server response
    let mut buffer = [0; 1024];
    let nbytes = stream.read(&mut buffer)?;
    println!("{}", String::from_utf8_lossy(&buffer[..nbytes]));

    Ok(())
}
455 chars
18 lines

In this example, we connect to a TCP server at address 127.0.0.1:8080. We then send a JSON message using the write() method of the stream object. To read the server response, we use the read() method to read data into a buffer, and then convert the buffer to a string.

Note that you will need to handle errors when working with TCP connections and IO operations. The std::io::Result type is used in this example to propagate IO errors to the caller.

related categories

gistlibby LogSnag