Rust网络编程(1)-tcp和udp

tcp和udp开发

1. tcp

客户端输入信息,服务器端接收,并反馈给客户端

1.1 tcp服务器端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use std::net::{TcpListener,TcpStream};
use std::thread;
use std::time;
use std::io::{self,Read,Write};
use std::time::Duration;

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:9999")?;
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(())
}

1.2 tcp服务器端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:9999")?;
for _ in 0..10{
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read");
stream.write(input.as_bytes()).expect("Failed to wrote");
let mut reader = BufReader::new(&stream);
let mut buffer: Vec<u8> = Vec::new();
reader.read_until(b'\n',&mut buffer).expect("Failed to read into buffer");
println!("read from server : {}",str::from_utf8(&buffer).unwrap());
println!(" ")
}
Ok(())
}

2. udp

2.1 udp客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::net::UdpSocket;
use std::{io,str};
fn main() -> io::Result<()>{
let socket = UdpSocket::bind("127.0.0.1:8888")?;
socket.connect("127.0.0.1:9999")?;
loop{
let mut input = String::new();
io::stdin().read_line(&mut input)?;
socket.send(input.as_bytes())?;
let mut buffer = [0u8;1500];
socket.recv_from(&mut buffer)?;
println!("recv:{}",str::from_utf8(&buffer).expect("Could not write buffer as string"));
}
}

2.2 udp服务器端

1
2
3
4
5
6
7
8
9
10
11
12
13
use std::net::UdpSocket;

fn main() -> std::io::Result<()> {
let socket = UdpSocket::bind("127.0.0.1:9999")?;
loop {
let mut buf = [0u8; 1500];
let (amt, src) = socket.recv_from(&mut buf)?;
println!("size = {}", amt);
let buf = &mut buf[..amt];
buf.reverse();
socket.send_to(buf,src)?;
}
}

总结

本文编辑完毕

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信