rust tcp server and client 通信

180it 2023-03-05 AM 609℃ 0条

tcpclient

use std::io::Write;
use std::net::TcpStream;
use std::io;
fn main() {
    // 连接TCP服务器
    let mut client = TcpStream::connect("127.0.0.1:9999").expect("连接失败!");
    println!("请输入您要发送到服务器的消息:");
    loop {
        let mut input = String::new();
        // 读取用户输入内容
        let size = io::stdin().read_line(&mut input).expect("读取命令行输入失败!");
        // 发送到TCP服务器
        client.write(&input.as_bytes()[..size]).expect("发送到TCP服务器失败!");
    }
}

tcpserver

use std::io::Write;
use core::str::from_utf8;
use std::io::{Error, Read};
use std::net::{TcpListener,TcpStream};
fn handle_client(mut stream: TcpStream) -> Result<(), Error>{
    // 定义512 字节 buffer 数组 并且初始化成0
    let mut buf = [0;512];
    loop{
        // 读取内容
        let len = stream.read(&mut buf).unwrap();
        if len == 0 {
            break;
        }
        println!("read {} bytes {:?}", len, from_utf8(&buf[..len]));
    }
    Ok(())
}
fn main() {
    // 创建TCP服务器
    let listener = TcpListener::bind("127.0.0.1:9999").expect("创建失败!");
    // 接收客户端消息
    for stream in listener.incoming() {
        // 异步线程处理消息
        std::thread::spawn(move || {
            handle_client(stream.unwrap()).expect("处理失败!");
        });
    }
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

rust tcp server and client 通信