Skip to content

Commit 03042d8

Browse files
committed
Non-blocking TCP logic, option 3
1 parent 1af0e99 commit 03042d8

File tree

1 file changed

+12
-23
lines changed

1 file changed

+12
-23
lines changed

src/tcp.rs

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
use std::io::ErrorKind::WouldBlock;
2-
use std::sync::{Arc, Mutex};
32
use std::time::Duration;
43

54
use byteorder::{BigEndian, ByteOrder};
@@ -8,34 +7,24 @@ use std::net::{TcpListener, TcpStream};
87
use std::str;
98
use std::thread;
109

11-
fn bind(connections: Arc<Mutex<Vec<TcpStream>>>) {
12-
thread::spawn(move || {
13-
let listener = TcpListener::bind("127.0.0.1:2593").unwrap();
14-
15-
for stream in listener.incoming() {
16-
let mut connections = connections.lock().unwrap();
17-
let stream = stream.unwrap();
18-
let addr = stream.peer_addr().unwrap();
19-
stream
20-
.set_read_timeout(Some(Duration::from_nanos(1)))
21-
.expect("set_read_timeout call failed");
22-
println!("Connection received from: {}", addr);
23-
connections.push(stream);
24-
}
25-
});
26-
}
27-
2810
pub fn start() {
29-
let connections: Vec<TcpStream> = vec![];
30-
31-
let connections = Arc::new(Mutex::new(connections));
11+
let listener = TcpListener::bind("127.0.0.1:2593").unwrap();
12+
listener
13+
.set_nonblocking(true)
14+
.expect("Cannot set non-blocking");
3215

33-
bind(Arc::clone(&connections));
16+
let mut connections: Vec<TcpStream> = vec![];
3417

3518
loop {
3619
thread::sleep(Duration::from_millis(1));
3720

38-
let mut connections = connections.lock().unwrap();
21+
if let Ok((stream, addr)) = listener.accept() {
22+
println!("Connection received from: {}", addr);
23+
stream
24+
.set_read_timeout(Some(Duration::from_nanos(1)))
25+
.expect("set_read_timeout call failed");
26+
connections.push(stream);
27+
}
3928

4029
connections.retain_mut(|stream| {
4130
let mut buffer = [0; 1024];

0 commit comments

Comments
 (0)