Created
May 28, 2021 02:42
-
-
Save libchaos/051412b9200b205269b82657f8cef5dd to your computer and use it in GitHub Desktop.
rust tpc server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread; | |
use std::net::{TcpListener, TcpStream, Shutdown}; | |
use std::io::{Read, Write}; | |
use std::str; | |
fn handle_client(mut stream:TcpStream) { | |
let mut data = [0 as u8; 50]; // 设置50个字节的数据缓冲区, 传输的数据被按50个字节切割 | |
while match stream.read(&mut data) { // match表达式返回true或者false 控制空循环 | |
Ok(size) => { // 当前的数据缓冲块的长度 | |
println!("size is {}", size); | |
stream.write(&data[0..size]).unwrap(); //向客户端echo数据 | |
let mut signal = true; // 设置退出信号 true为不退出 | |
let mut content = ""; // 当前数据块的内容 | |
if !str::from_utf8(&data[0..size]).is_err() { | |
content = str::from_utf8(&data[0..size]).unwrap(); // 将数据块的内容解码为utf8的&str类型的字符串 | |
} | |
if content.trim() == "close" { // 判断当前数据块的字符串是否等于close | |
println!("content is {}", &content); | |
println!("收到退出信号 {}", stream.peer_addr().unwrap()); // 打印客户端地址和端口 | |
stream.shutdown(Shutdown::Both).unwrap(); | |
signal = false; // 设置退出信号为false | |
} | |
signal // 返回退出信号, true 为不退出 false 为退出 | |
}, | |
Err(_) =>{ // 未能或者数据缓冲块的长度,出现错误 | |
println!("出现错误 中断连接 {}", stream.peer_addr().unwrap()); | |
stream.shutdown(Shutdown::Both).unwrap(); // 关闭此连接的读写通道 | |
false | |
} | |
} {} | |
} | |
fn main() { | |
let listener = TcpListener::bind("0.0.0.0:3333").unwrap(); // 创建一个tcp服务器 监听在3333端口 | |
println!("服务器监听在3333端口。。。。"); | |
for stream in listener.incoming() { // 迭代每一个连接 | |
match stream { // 匹配连接 | |
Ok(stream) =>{ | |
println!("新连接建立 {}", stream.peer_addr().unwrap()); | |
thread::spawn(move || { | |
handle_client(stream) // 利用线程处理连接 | |
}); | |
}, | |
Err(e) => { | |
println!("错误: {}", e); | |
} | |
} | |
} | |
drop(listener); // 关闭服务器 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment