当前位置:网站首页>Rust standard library - implement a TCP service, and rust uses sockets
Rust standard library - implement a TCP service, and rust uses sockets
2022-07-25 06:58:00 【Xijing swordsman】
List of articles
Rust- Use socket
Rust actual combat - Use socket networking API ( One )
Reference resources URL: https://www.jianshu.com/p/d1048d0b687f
Use Rust Write a simple one Socket The server (1):Rust Load the configuration under
Reference resources URL: https://my.oschina.net/u/4528547/blog/4951186
rust transfer libc The function in
Official website rust Adjustable libc:http://www.eclipse.org/paho/files/rustdoc/libc/index.html#
Rust actual combat - Use socket networking API ( One )
Reference resources URL:https://www.jianshu.com/p/d1048d0b687f
use std::os::raw::c_char;
use std::ffi::CStr;
extern {
pub fn gethostname(name: *mut c_char, len: usize) -> i32;
}
fn main() {
let len = 255;
let mut buf = Vec::<u8>::with_capacity(len);
let ptr = buf.as_mut_ptr() as *mut c_char;
unsafe {
gethostname(ptr, len);
println!("{:?}", CStr::from_ptr(ptr));
}
}
extren Express “ External block (External blocks)”, Used to declare external non Rust Symbols in the library . I We need to use Rust Other functions , such as libc , It needs to be in extren Define the functions you need , Then you can use external functions just like local functions , The compiler will be responsible for helping us transform . however , Calling an external function is unsafe Of , The compiler does not provide sufficient assurance , So put it in unsafe In block .
“gethostname” Function in C The prototype in the header file is :
int gethostname(char *name, size_t len);
stay Linux 64 A platform ,C Medium int Corresponding to Rust Medium int,size_t Corresponding Rust Medium usize, but C Medium char And Rust Medium char It's completely different ,C Medium char Always be i8 perhaps u8, and Rust Medium char It's a unicode Scalar values . You can also check the standard library . For the pointer ,Rust Bare pointer in And C The pointer in is almost the same ,Rust Of *mut Corresponding C Normal pointer to ,*const Corresponding C Of const The pointer . So we will match the types one by one , Parameter names of functions are not required to be consistent .
Please check the original !
Rust actual combat - Use socket networking API ( One )
Reference resources URL: https://www.jianshu.com/p/d1048d0b687f
rust Operation socket API
Official website rust Adjustable libc:http://www.eclipse.org/paho/files/rustdoc/libc/index.html#
Rust actual combat - Use socket networking API ( One )
https://www.jianshu.com/p/d1048d0b687f
Speaking of sockets API, It mainly includes TCP、UDP、SCTP Related functions ,I/O Reuse functions and advanced I/O function . Most of these functions Rust There is nothing in the standard , If the standard library cannot meet your needs , You can call it directly libc The function in . actually , Standard library , The Internet , Basically right libc Encapsulation of related functions in .
Please check the original !
Rust actual combat - Use socket networking API ( One )
Reference resources URL: https://www.jianshu.com/p/d1048d0b687f
Rust Standard library
Standard library :https://doc.rust-lang.org/std/
Standard library net modular :https://doc.rust-lang.org/std/net/index.html
Rust The standard library is portable Rust The foundation of software , It is a set of minimum shared abstractions that have been tested in practice , Applicable to a wider range of Rust The ecological system . It provides core types , Such as Vec and Option、 Library defined language primitives 、 Standard macro 、I/O and Multithreading and other operations , wait .
std By default, it can be used for all Rust crate. therefore , Sure use Through the path in the statement Access the standard library std, Such as use std::env.
Rust Standard library net
Standard library net modular :https://doc.rust-lang.org/std/net/index.html
Rust Standard library net modular To provide for TCP / UDP Communication network primitive .
The module is composed of transmission control and user datagram protocol and IP And the type of socket address provide network functions .
rust Achieve one tcp server
rust Achieve one tcp server
Reference resources URL: https://blog.csdn.net/by186/article/details/117234191
Rust Web The whole development of the stack - 1 structure TCP Server
Reference resources URL: https://blog.csdn.net/weixin_51487151/article/details/123784175
【 recommend , The author also has stress tests 】Rust Write a simple , Highly concurrent http service ( Pure standard library , After compiling 168kb), Concurrent stress tests are attached
Reference resources URL: https://blog.csdn.net/qq_26373925/article/details/109187251
Server side
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:7878").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(())
}
Use TcpListener monitor Socket request
Use Read/Write Trait Conduct Socket Data reading and writing
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:7878")?;
for _ in 0..1000 {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read");
stream.write(input.as_bytes()).expect("failed to write");
let mut reader =BufReader::new(&stream);
let mut buffer: Vec<u8> = Vec::new();
reader.read_until(b'\n',&mut buffer)?;
println!("read form server:{}",str::from_utf8(&buffer).unwrap());
println!("");
}
Ok(())
}
边栏推荐
- The relationship between Informatics, mathematics and Mathematical Olympiad (July 19, 2022) C
- Shell run command
- [cann training camp] play with the one-stop plan of cann target detection and recognition - learning notes 1 (initial experience)
- labelme标注不同物体显示不同颜色以及批量转换
- C#控件开源库:MetroFramework的下载
- Analysis of the calling principle of Changan chain solid smart contract
- Do you know the same period last year in powerbi
- JS data type judgment - Case 6 delicate and elegant judgment of data type
- When the graduation season comes, are you ready? What are we going to do
- Can communication test based on STM32: turn the globe
猜你喜欢

Kyligence Li Dong: from the data lake to the index middle stage, improve the ROI of data analysis

【transformer】DeiT

Software engineering in Code: regular expression ten step clearance
![[C language] program environment and preprocessing](/img/d6/d59a0d8d286ea9408043d8ad1e1348.png)
[C language] program environment and preprocessing

【剑指Offer】模拟实现atoi

LeetCode46全排列(回溯入门)

Rongyun launched a real-time community solution and launched "advanced players" for vertical interest social networking

【每日一题】1184. 公交站间的距离

【terminal】x86 Native Tools Command Prompt for VS 2017

C#开源控件MetroFramework Demo项目下载和运行
随机推荐
A scene application of 2D animation
[C language] document processing and operation
10 minutes to understand how JMeter plays with redis database
【知识总结】分块和值域分块
Not only log collection, but also the installation, configuration and use of project monitoring tool sentry
ArgoCD 用户管理、RBAC 控制、脚本登录、App 同步
Precautions for starting up the server of Dahua Westward Journey
Will eating fermented steamed bread hurt your body
代码中的软件工程:正则表达式十步通关
【剑指Offer】模拟实现atoi
The income of bank financial management is getting lower and lower. Now which financial products have high income?
knapsack problem
100 GIS practical application cases (seventeen) - making 3D map based on DEM
常吃发酵馒头是否会伤害身体
Save the sqoop run template
【terminal】x86 Native Tools Command Prompt for VS 2017
Addition, deletion, modification and query of DOM elements
Octopus network community call 1 starts Octopus Dao construction
Devops has been practiced for many years. What is the most painful thing?
Hierarchical reinforcement learning: a comprehensive survey