51nod 2518 和为S

1198:逆波兰表达式

  返回  

Rust tcp 客户端和服务端实现

2021/8/21 19:57:33 浏览:

客户端

use std::io::{self, Write};
use std::net::TcpStream;

fn main() {
  let mut stream = TcpStream::connect("127.0.0.1:8080").expect("connect failed");

  loop {
    let mut input = String::new();
    let size = io::stdin().read_line(&mut input).expect("read line failed");

    stream
      .write(&input.as_bytes()[..size])
      .expect("write failed");
  }
}

服务端

use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::str;
use std::thread;

fn handle_client(mut stream: TcpStream) {
    let mut buf = [0; 128];
    loop {
        // 读取内容
        let len = stream.read(&mut buf).unwrap();
        if len == 0 {
            println!("ok");
            break;
        }
        // 输出读取到的内容
        println!("read {} bytes: {:?}", len, str::from_utf8(&buf[..len]));
    }
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    // 对每一个连接开启一个线程进行处理
    for stream in listener.incoming() {
        thread::spawn(move || {
            handle_client(stream.unwrap());
        });
    }
    println!("Hello, world!");
}

联系我们

如果您对我们的服务有兴趣,请及时和我们联系!

服务热线:18288888888
座机:18288888888
传真:
邮箱:888888@qq.com
地址:郑州市文化路红专路93号