跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Rust] rust TcpStream 为什么设计读写一体

发表于
fn main(){
    let mut ts1=TcpStream::connect(("127.0.0.1", 6666)).unwrap();
    //读写全都在一起
    ts1.write("hello".as_bytes()).unwrap();
    let mut buf=[0;1024];
    ts1.read(&mut buf).unwrap();
    //这样设计,在一些情况不方便

    //1 两个 TcpStream 需要全双工拷贝
    let mut ts2=TcpStream::connect(("127.0.0.1", 6667)).unwrap();
    //这里不得不进行 clone
    let mut ts11=ts1.try_clone().unwrap();
    let mut ts22=ts2.try_clone().unwrap();
    thread::spawn(move||{
       std::io::copy(&mut ts1,&mut ts2).unwrap();
    });

    thread::spawn(move||{
        std::io::copy(&mut ts22,&mut ts11).unwrap();
    });
    // 以下两种情况以开发一个 http server 为场景
    //2 当需要将 TcpStream 使用 BufReader  和  BufWriter 封装构造一个结构体给上层使用
    
    struct Req{
        br:BufReader<TcpStream>,
        bw:BufWriter<TcpStream>,
    }
    //3 如果不进行 buf 封装,底层处理也不能使用 buf 进行读取,因为 buf 读取可能会读取超过底层处理的数据的长度,这样底层
    // 只能使用非 buf 方式进行读取,效率就比较低下
    struct Req1{
        ts:TcpStream
    }
    
    
}

目前我能想到的 TcpStream 读写一体,是为了 drop 时候自动关闭 tcp 连接,但是这样确实带来了诸多不便。 同样 BufReader 、BufWriter 在 new 的时候传&TcpStream ,不能生成一个具有所有权的 br 、bw ,会依赖&TcpStream 。TcpStream 为什么不提供一个 getWriter 和 getReader 两个分离的函数呢?

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.