服务端

    1. use std::thread;
    2. use std::net::{TcpListener, TcpStream, Shutdown};
    3. use std::io::{Read, Write};
    4. fn handle_client(mut stream: TcpStream) {
    5. let mut data = [0 as u8; 50]; // using 50 byte buffer
    6. while match stream.read(&mut data) {
    7. Ok(size) => {
    8. // echo everything!
    9. stream.write(&data[0..size]).unwrap();
    10. true
    11. },
    12. Err(_) => {
    13. println!("An error occurred, terminating connection with {}", stream.peer_addr().unwrap());
    14. stream.shutdown(Shutdown::Both).unwrap();
    15. false
    16. }
    17. } {}
    18. }
    19. fn main() {
    20. let listener = TcpListener::bind("0.0.0.0:3333").unwrap();
    21. // accept connections and process them, spawning a new thread for each one
    22. println!("Server listening on port 3333");
    23. for stream in listener.incoming() {
    24. match stream {
    25. Ok(stream) => {
    26. println!("New connection: {}", stream.peer_addr().unwrap());
    27. thread::spawn(move|| {
    28. // connection succeeded
    29. handle_client(stream)
    30. });
    31. }
    32. Err(e) => {
    33. println!("Error: {}", e);
    34. /* connection failed */
    35. }
    36. }
    37. }
    38. // close the socket server
    39. drop(listener);
    40. }

    客户端

    1. use std::net::{TcpStream};
    2. use std::io::{Read, Write};
    3. use std::str::from_utf8;
    4. fn main() {
    5. match TcpStream::connect("localhost:3333") {
    6. Ok(mut stream) => {
    7. println!("Successfully connected to server in port 3333");
    8. let msg = b"Hello99999";
    9. stream.write(msg).unwrap();
    10. println!("Sent Hello, awaiting reply...");
    11. let mut data = [0 as u8; 10]; // using 6 byte buffer
    12. match stream.read_exact(&mut data) {
    13. Ok(_) => {
    14. if &data == msg {
    15. println!("Reply is ok!");
    16. let text = from_utf8(&data).unwrap();
    17. println!("Unexpected reply: {}", text);
    18. } else {
    19. let text = from_utf8(&data).unwrap();
    20. println!("Unexpected reply: {}", text);
    21. }
    22. },
    23. Err(e) => {
    24. println!("Failed to receive data: {}", e);
    25. }
    26. }
    27. },
    28. Err(e) => {
    29. println!("Failed to connect: {}", e);
    30. }
    31. }
    32. println!("Terminated.");
    33. }