当前位置:网站首页>Rust: a simple example of TCP server and client
Rust: a simple example of TCP server and client
2022-04-23 18:04:00 【Xu Yeping】
Rust: Tcp A simple example of server and client
Don't talk much nonsense , Go straight to the chestnuts :
1 Server-side code
use std ::net::{
TcpListener,TcpStream};
use std::thread;
use std::time;
use std::io;
use std::io::{
Read,Write};
fn handle_client(mut stream: TcpStream) -> io::Result<()>{
let mut buf = [0;512];
for _ in 0..1000{
let bytes_read = stream.read(&mut buf)?;
if bytes_read == 0{
return Ok(());
}
stream.write(&buf[..bytes_read])?;
thread::sleep(time::Duration::from_secs(1));
}
Ok(())
}
fn main() -> io::Result<()>{
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();
for stream in listener.incoming() {
let stream = stream.expect("failed");
let handle = thread::spawn(move || {
handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}",error))
});
thread_vec.push(handle);
}
for handle in thread_vec {
handle.join().unwrap();
}
Ok(())
}
2 client
use std::io::{
self,prelude::*,BufReader,Write};
use std::net::TcpStream;
use std::str;
fn main() -> io::Result<( )> {
let mut stream = TcpStream::connect("127.0.0.1:8080")?;
for i in 0..3 {
println!("i = {}", i);
let mut input = String::new();
println!("read_line");
io::stdin().read_line(&mut input).expect("Failed to read");
println!("write");
stream.write(input.as_bytes()).expect("failed to write");
println!("BufReader::new())");
let mut reader =BufReader::new(&stream);
let mut buffer: Vec<u8> = Vec::new();
println!("read_until");
reader.read_until(b'\n',&mut buffer)?;
println!("read form server:{}",str::from_utf8(&buffer).unwrap());
println!("");
}
Ok(())
}
版权声明
本文为[Xu Yeping]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230544498257.html
边栏推荐
- .105Location
- Realization of consumer gray scale
- Summary of floating point double precision, single precision and half precision knowledge
- Read excel, int digital time to time
- 587. Install fence / Sword finger offer II 014 Anagrams in strings
- Implementation of object detection case based on SSD
- Crawl lottery data
- Use of list - addition, deletion, modification and query
- Theory and practice of laser slam in dark blue College - Chapter 2 (odometer calibration)
- ES6 face test questions (reference documents)
猜你喜欢
Docker 安装 Redis
Fashion classification case based on keras
Examination question bank and online simulation examination of the third batch (main person in charge) of special operation certificate of safety officer a certificate in Guangdong Province in 2022
Go的Gin框架学习
MySQL auto start settings start with systemctl start mysqld
MySQL_ 01_ Simple data retrieval
Auto.js 自定义对话框
QTableWidget使用讲解
String function in MySQL
Gobang game based on pyGame Library
随机推荐
Gobang game based on pyGame Library
消费者灰度实现思路
ES6 face test questions (reference documents)
Notes on common basic usage of eigen Library
Docker installation MySQL
Halo 开源项目学习(二):实体类与数据表
MySQL 中的字符串函数
Dock installation redis
Realsense selection comparison d455 d435i d415 t265 3D hardware comparison
Re expression régulière
2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition
QTableWidget使用讲解
Generate verification code
Calculation of fishing net road density
2022江西光伏展,中国分布式光伏展会,南昌太阳能利用展
Installation du docker redis
Eigen learning summary
Arcpy adds fields and loop assignments to vector data
Implementation of image recognition code based on VGg convolutional neural network
Identification verification code