Rust: Tcp编程Demo

最基本的Hello World示例:

TcpServer端:

use std::{net::TcpListener, io::{Read, Write}};

fn main() {
    //绑定本机3000端口
    let listener = TcpListener::bind("127.0.0.1:3000").unwrap();
    println!("Running on port 3000...");

    //当有client连接上来时
    for stream in listener.incoming(){
        let mut stream = stream.unwrap();
        println!("Connection established!");
        //创建1k的缓存区
        let mut buffer = [0;1024];
        //读取client发过来的内容
        stream.read(&mut buffer).unwrap();
        //原样送回去(相当于netty的EchoServer)
        stream.write(&mut buffer).unwrap();
    }
}

  

TcpClient端:

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

fn main() {
    //连接到server
    let mut stream = TcpStream::connect("127.0.0.1:3000").unwrap();
    //发送字符串
    stream.write("hello,rust.欢迎使用Rust".as_bytes()).unwrap();

    //创建1k的缓冲区,用于接收server发过来的内容
    let mut buffer = [0;1024];
    //读取server发过来的内容
    stream.read(&mut buffer).unwrap();

    //打印接收到的内容(注:如果收到的实际内容小于1k,后面的部分默认全是\u{0}填充,所以要trim_matches去掉)
    println!("Response from server:{:?}",str::from_utf8(&buffer).unwrap().trim_matches('\u{0}'));

}

 

posted @ 2021-12-26 20:14  菩提树下的杨过  阅读(805)  评论(0编辑  收藏  举报