标签:mut UDP Mio server let str 服务器 poll event
环境
- Time 2022-01-08
- Rust 1.57.0
- mio 0.8
概念
参考:https://github.com/tokio-rs/mio/blob/master/examples/tcp_server.rs
将客户端发送的消息转为大写后返回。
UDP 服务器基本功能实现完成,只能做练习使用,不可用于生产环境。
示例
监听端口
const SERVER: Token = Token(0);
fn main() -> io::Result<()> {
let addr = "127.0.0.1:4444".parse().unwrap();
let mut server = UdpSocket::bind(addr)?;
let mut poll = Poll::new()?;
let mut events = Events::with_capacity(128);
poll.registry()
.register(&mut server, SERVER, Interest::READABLE)?;
loop {
poll.poll(&mut events, None)?;
for event in events.iter() {
handle(event, &server)?;
}
}
}
处理
fn handle(event: &Event, server: &UdpSocket) -> io::Result<()> {
if event.token() != SERVER {
return Ok(());
}
let mut buffer = vec![0; 4096];
loop {
match server.recv_from(&mut buffer) {
Ok((size, address)) => {
println!("客户端: {}", address);
let received = &buffer[..size];
let str = from_utf8(received).unwrap();
println!("收到数据:{}", str);
server.send_to(str.to_ascii_uppercase().as_bytes(), address)?;
}
Err(e) if e.kind() == WouldBlock => break,
Err(err) => return Err(err),
}
}
Ok(())
}
总结
使用 UDP 协议实现了将客户端发送的内容进行大写转换后返回。
附录
完整代码
use mio::{event::Event, net::UdpSocket, Events, Interest, Poll, Token};
use std::{
io::{self, ErrorKind::WouldBlock},
str::from_utf8,
};
const SERVER: Token = Token(0);
fn main() -> io::Result<()> {
let addr = "127.0.0.1:4444".parse().unwrap();
let mut server = UdpSocket::bind(addr)?;
let mut poll = Poll::new()?;
let mut events = Events::with_capacity(128);
poll.registry()
.register(&mut server, SERVER, Interest::READABLE)?;
loop {
poll.poll(&mut events, None)?;
for event in events.iter() {
handle(event, &server)?;
}
}
}
fn handle(event: &Event, server: &UdpSocket) -> io::Result<()> {
if event.token() != SERVER {
return Ok(());
}
let mut buffer = vec![0; 4096];
loop {
match server.recv_from(&mut buffer) {
Ok((size, address)) => {
println!("客户端: {}", address);
let received = &buffer[..size];
let str = from_utf8(received).unwrap();
println!("收到数据:{}", str);
server.send_to(str.to_ascii_uppercase().as_bytes(), address)?;
}
Err(e) if e.kind() == WouldBlock => break,
Err(err) => return Err(err),
}
}
Ok(())
}
标签:mut,UDP,Mio,server,let,str,服务器,poll,event
来源: https://www.cnblogs.com/jiangbo44/p/15940548.html
本站声明:
1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。