Rsut 全栈开发-WebAssembly

我爱海鲸 2024-07-19 15:28:17 rust学习

简介sqlx、Actix、Web App、rust学习资源

rust学习资源:https://github.com/WumaCoder/rust-boom

https://github.com/hiiiiiiixiaohui/rs-full-stack-project

1、视频:前戏:课程简介_哔哩哔哩_bilibili

技术栈:

2、自建TCP Server

std::net模块

标准库的std::net模块,提供网络基本功能

支持 TCP和UDP通信

TcpListener和 TcpStream

cargo new s1 & cd s1
cargo new tcpserver
cargo new tcpclient
code .

修改s1目录中的Cargo.toml:

[workspace]

resolver="2"

members=["tcpclient","tcpserver"]

打开tcpserver中的main函数:

use std::net::TcpListener;

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

    println!("Running on port 3000。。。");


    for stream in listener.incoming()  {
        let _stream = stream.unwrap();
        println!("Connection established!")
    }
}

执行命令:cargo run -p tcpserver(指定包执行)

tcpclient中的main函数:

use std::net::TcpStream;


fn main() {
    let _stream = TcpStream::connect("localhost:3000").unwrap();

}

执行命令:cargo run -p tcpclient(指定包执行)

在之前的tcpserver中的terminal中就能够监听到tcp的链接,然后打印Connection established!

修改tcpserver中的main:

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

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

    println!("Running on port 3000。。。");


    for stream in listener.incoming()  {
        let mut  stream = stream.unwrap();
        println!("Connection established!");

        let mut buffer = [0;1024];

        stream.read(&mut buffer).unwrap();
        stream.write(&mut buffer).unwrap();

    }
}

修改tcpclient中的main:

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


fn main() {
    let mut  stream = TcpStream::connect("localhost:3000").unwrap();
    stream.write("Hello".as_bytes()).unwrap();

    let mut buffer = [0;5];

    stream.read(&mut buffer).unwrap();

    println!(
        "Response from server {:?}",
        ss::from_utf8(&mut buffer).unwrap()
    );

}

执行命令:cargo run -p tcpserver(指定包执行)

执行命令:cargo run -p tcpclient(指定包执行)

然后服务端就能够接收到hello这个单词了

3、构建Http Server

 

你好:我的2025