codecraze
codecraze
CodeCraze
2 posts
All About Tech!
Don't wanna be here? Send us removal request.
codecraze · 2 years ago
Text
0 notes
codecraze · 2 years ago
Text
TCP Server Rust
This is a Rust program that sets up a TCP server to listen for incoming client connections on port 5566. When a client connects to the server and sends a JSON string representing an Employee object, the server deserializes the JSON string and prints the employee's first name to the console.
Here's a breakdown of the code:
The use statements at the top of the file import the necessary Rust modules and dependencies. The serde module is used for serializing and deserializing data, and the std::io and std::net modules are used for handling I/O and network connections.
The Employee struct is defined with three fields: first_name, last_name, and employee_id. The #[derive(Serialize, Deserialize)] attribute macros are used to generate the serde implementations for the struct, which allow it to be serialized and deserialized to and from JSON.
The main function sets up a TCP server using the TcpListener struct and listens for incoming client connections on port 5566. When a client connection is received, a new thread is spawned to handle the connection.
The process_object function is called in the new thread to handle the client connection. The function reads the incoming data from the client, deserializes the JSON string to an Employee object, and prints the employee's first name to the console.
The program uses the try_clone method to create a new handle to the same stream, which allows the function to read the incoming data without consuming the original stream.
The program uses Rust's Result type to handle errors that may occur during I/O operations or JSON deserialization.
Overall, this code demonstrates how to set up a TCP server in Rust and handle incoming client connections, as well as how to serialize and deserialize data to and from JSON using the serde library.
Here is main.rs
Tumblr media Tumblr media
Here is Cargo.toml
Tumblr media
Run the following command in your project directory to build and run the server:
cargo run
Open a new terminal window and connect to the server using a TCP client, such as netcat or telnet. For example, you can run the following command to connect to the server:
telnet 127.0.0.1 5566
Once connected, you can send a message or object to the server. For example, to send a message, simply type a string and press Enter. The server will respond with an acknowledgement message.
To send an object, create a JSON string representing an Employee object and send it to the server using the same connection. The server will deserialize the JSON string and print the employee's first name.
To stop the server, press Ctrl+C in the terminal window where the server is running.
2 notes · View notes