Commit f16bdb28 by xgrowingpains

init

parent c1c26c64
Pipeline #4501 failed with stages
in 0 seconds
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "tcpserver"
version = "0.1.0"
[package]
name = "tcpserver"
version = "0.1.0"
authors = ["root"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
use std::io::{Error, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time;
use std::str;
fn read_byte(_url: &String) -> Result<(), &'static str>{
Err("input error.")
}
//循环
fn handle_client(mut stream: TcpStream) -> Result<(), Error>{
let mut buf = [0; 512];
//100
loop {
//eprintln!("buf ==========={:?}", buf);
//输入内容字节数
let bytes_read = stream.read(&mut buf)?;
//字节数为0则结束
match read_byte(bytes_read) {
Ok(k) => {
stream.read(&mut buf)?;
},
Err(e) => {
println!("Failed to open the file.");
}
};
// if bytes_read == 0 {
// return Ok(());
// }
//字节数
println!("format {} arguments", bytes_read);
//写回到stream中
stream.write(&buf[..bytes_read])?;
//转字符串打印
println!("{}", str::from_utf8(&buf).expect("Could not write buffer as string"));
//休眠1秒钟
thread::sleep(time::Duration::from_secs(1 as u64));
}
//Ok(())
}
fn main() -> std::io::Result<()> {
//创建监听器
let listener = TcpListener::bind("127.0.0.1:8080")?;
// let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();
//打印监听器
eprintln!("listener ==={:?}", listener);
for stream in listener.incoming() {
//如果值不存在则提示错误
let stream = stream.expect("failed!");
//spawn 函数创建新进程,
let handle = thread::spawn( || {
//调用handle_client,有错误抛出异常unwrap_or_else类似match
handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error));
//Err(error);
});
eprintln!("handle ==========={:?}", handle);
}
Ok(())
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment