TcpStreams and network programming

Hi all! I’m new to socket / network programming and trying to learn it in Rust. I have a simple client and server which communicate by sending JSON messages (using serde_json for this). For sending the message to TcpStream, I’m using serde_json::to_writer(stream, &message) and on the server side, I’m reading the message by serde_json::from_reader(stream).

All of this works fine but I want to a way for the server to tell the client that they sent the wrong message (say, a missing field), how would I go about doing that?

On the server, is it okay to write to the same TcpStream from which its reading or is there another way?

TCP streams are bi-directional - you can read and write on them.

I would create a json format that contains a "error" field, which will contain the error message if one occurred.

For example

#[derive(Serialize, Deserialize)]
struct MyStruct {
   user_req: String,
}

#[derive(Serialize, Deserialize)]
struct MyJsonError {
    error: String,
}

fn handle_client(...) {
    let client_request: MyStruct = match serde_json::from_reader(client_socket) {
        Ok(v) => v,
        Err(err) => {
            // failed to parse, send error.
            serde_json::to_writer(client_socket, MyJsonError{
                msg: err.to_string(),
            });
            return; // exit function.
        }
    };
    // continue processing request.
}

As @sfackler said, tcp streams are bi-directional. So you can read & write on the same stream (both client & server).