-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathlistener.rs
More file actions
61 lines (53 loc) · 1.53 KB
/
listener.rs
File metadata and controls
61 lines (53 loc) · 1.53 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::{net::SocketAddr, sync::Arc};
use anyhow::Context;
use flume::Sender;
use tokio::net::{TcpListener, TcpStream};
use crate::{
connection_worker::Worker, initial_handler::NewPlayer, options::Options,
player_count::PlayerCount,
};
/// Listens for and accepts incoming connections.
pub struct Listener {
listener: TcpListener,
options: Arc<Options>,
player_count: PlayerCount,
new_players: Sender<NewPlayer>,
}
impl Listener {
pub async fn start(
options: Arc<Options>,
player_count: PlayerCount,
new_players: Sender<NewPlayer>,
) -> anyhow::Result<()> {
let listener = TcpListener::bind(format!("{}:{}", options.bind_address, options.port))
.await
.context("failed to bind to port - maybe a server is already running?")?;
let listener = Listener {
listener,
options,
player_count,
new_players,
};
tokio::task::spawn(async move {
listener.run().await;
});
Ok(())
}
async fn run(mut self) {
loop {
if let Ok((stream, addr)) = self.listener.accept().await {
self.accept(stream, addr).await;
}
}
}
async fn accept(&mut self, stream: TcpStream, addr: SocketAddr) {
let worker = Worker::new(
stream,
addr,
Arc::clone(&self.options),
self.player_count.clone(),
self.new_players.clone(),
);
worker.start();
}
}