006 Rust 網路程式設計,mio 庫介紹

linghuyichong發表於2020-04-25

標準庫也缺乏對套接字和連線的細粒度控制,例如設定SO_REUSEADDR。mio庫則提供了很多方法來解決這些問題。

依賴

[dependencies]
mio = { version = "0.7.0", features = ["os-poll", "tcp"]}

原始碼示例

use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};

const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);

fn main() -> std::io::Result<()> {
    let mut poll = Poll::new()?;
    let mut events = Events::with_capacity(128);

    // 建立server端socket
    let addr = "127.0.0.1:8080".parse().unwrap();
    let mut server = TcpListener::bind(addr)?;

    // 開始監聽該連結
    poll.registry()
        .register(&mut server, SERVER, Interest::READABLE)?;

    // 建立客戶端連結到服務端
    let mut client = TcpStream::connect(addr)?;

    // 監聽客戶端
    poll.registry()
        .register(&mut client, CLIENT, Interest::READABLE | Interest::WRITABLE)?;

    // 啟動迴圈
    loop {
        // 輪訓事件
        poll.poll(&mut events, None)?;

        // 處理事件
        let mut cnt = 0;
        for event in events.iter() {
            match event.token() {
                SERVER => {
                    let connection = server.accept();
                    println!("SERVER recv a connection! cnt = {}", cnt);
                    drop(connection);
                }
                CLIENT => {
                    if event.is_writable() {
                        println!("CLIENT write, cnt = {}", cnt);
                    }

                    if event.is_readable() {
                        println!("CLIENT read, cnt = {}", cnt);
                    }

                    return Ok(());
                }

                _ => unreachable!(),
            }
            cnt += 1;
        }
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章