标准库的 std::net 提供了相关实现。
TcpListener TcpStream

tcp server

  1. use std::io::{self, Read, Write};
  2. use std::net::{TcpListener, TcpStream};
  3. use std::thread;
  4. use std::time;
  5. fn handle_client(mut stream: TcpStream) -> io::Result<()> {
  6. // stream buffer
  7. let mut buf = [0; 512];
  8. for _ in 0..1000 {
  9. let bytes_read = stream.read(&mut buf)?;
  10. if bytes_read == 0 {
  11. return Ok(());
  12. }
  13. stream.write(&buf[..bytes_read])?;
  14. thread::sleep(time::Duration::from_secs(1));
  15. }
  16. Ok(())
  17. }
  18. fn main() -> io::Result<()> {
  19. let listener = TcpListener::bind("127.0.0.1:8080")?;
  20. let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();
  21. for stream in listener.incoming() {
  22. let stream = stream.expect("stream failed");
  23. let handle = thread::spawn(move || {
  24. handle_client(stream).unwrap_or_else(|error| eprintln!("{}", error))
  25. });
  26. thread_vec.push(handle);
  27. }
  28. for handle in thread_vec {
  29. handle.join().unwrap();
  30. }
  31. Ok(())
  32. }

client

  1. use std::io::{self, prelude::*, BufReader, Write};
  2. use std::net::TcpStream;
  3. use std::str;
  4. fn main() -> io::Result<()> {
  5. let mut stream = TcpStream::connect("127.0.0.1:8080")?;
  6. for _ in 0..10 {
  7. let mut input = String::new();
  8. io::stdin().read_line(&mut input).expect("Failed to read");
  9. stream.write(input.as_bytes()).expect("Failed to write");
  10. let mut reader = BufReader::new(&stream);
  11. let mut buffer: Vec<u8> = Vec::new();
  12. reader
  13. .read_until(b'\n', &mut buffer)
  14. .expect("Failed to read buffer");
  15. println!("read from server: {}", str::from_utf8(&buffer).unwrap());
  16. }
  17. println!("THE END");
  18. Ok(())
  19. }