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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
|
use websocket::{OwnedMessage,
sync::Server,
client::sync::Client,
server::{NoTlsAcceptor, InvalidConnection,
sync::AcceptResult}};
use std::net::{SocketAddr, ToSocketAddrs, TcpStream};
use std::sync::mpsc;
use std::sync::mpsc::{Sender, Receiver};
use super::lobby::Lobby;
use super::backend_connection::BackendConnection;
const PROTOCOL: &str = "tuesday";
type Token = u32;
#[derive(Debug)]
pub enum GameServerError {
BindError(std::io::Error),
HandshakeRequestError,
InvalidProtocolError,
AcceptError(std::io::Error)
}
pub struct GameServer {
addr: SocketAddr,
lobby: Lobby,
backend: BackendConnection,
}
pub struct GameClient {
addr: SocketAddr,
client: Client<TcpStream>,
}
impl GameClient {
fn from_raw(client: Client<TcpStream>) -> Result<Self, ()> {
let addr = client.peer_addr().map_err(|_| ())?;
info!("got a client connection from: {}", addr);
Ok(GameClient {
addr,
client,
})
}
fn require_token(&mut self) -> Option<Token> {
let message = self.client
.recv_message()
.ok()?;
if let OwnedMessage::Text(text) = message {
text.parse::<Token>().ok()
} else {
None
}
}
}
type ClientConnection = Result<GameClient, GameServerError>;
impl GameServer {
pub fn new<T: ToSocketAddrs>(addr: T) -> Self {
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
debug!("ws address: {}", addr);
info!("create lobby");
let lobby = Lobby::new();
let backend = BackendConnection::new("https://kobert.dev");
info!("got a C# backend connection");
GameServer {
addr,
lobby,
backend,
}
}
pub fn run(&self) -> Result<(), GameServerError> {
let reader = self.read_clients();
loop {
let mut connection = reader.recv().unwrap()?;
self.add_client(connection);
}
Ok(())
}
fn add_client(&self, mut client: GameClient) {
std::thread::spawn(move || {
println!("Token: {:?}", client.require_token());
loop { std::thread::sleep(std::time::Duration::from_millis(100)); }
});
}
fn read_clients(&self) -> Receiver<ClientConnection> {
let (s, r): (Sender<ClientConnection>, Receiver<ClientConnection>)
= mpsc::channel();
let addr = self.addr;
std::thread::spawn(move || {
let result = Self::handle_requests(addr, &s).or_else(|e| s.send(Err(e)));
});
r
}
fn handle_requests(addr: SocketAddr, s: &Sender<ClientConnection>) -> Result<(), GameServerError> {
let server = match Server::<NoTlsAcceptor>::bind(addr) {
Ok(v) => v,
Err(e) => {
error!("websocket binding error");
Err(GameServerError::BindError(e))?
},
};
info!("webserver is being launched");
for req in server {
s.send(Ok(Self::handle_request(req)?)).unwrap();
}
info!("webserver is being shut down");
Ok(())
}
fn handle_request(req: AcceptResult<TcpStream>) -> ClientConnection {
match req {
Ok(req) => {
if !req.protocols().contains(&PROTOCOL.to_string()) {
warn!("a client tried to connect without {} protocol", PROTOCOL);
req.reject().unwrap();
Err(GameServerError::InvalidProtocolError)
} else {
match req.use_protocol(PROTOCOL).accept() {
Ok(client) => {
match GameClient::from_raw(client) {
Ok(client) => Ok(client),
Err(_) => {
error!("could not create a client");
Err(GameServerError::HandshakeRequestError)
}
}
},
Err((_, e)) => {
warn!("client handshake failed");
Err(GameServerError::AcceptError(e))
}
}
}
},
Err(e) => {
warn!("invalid client request");
Err(GameServerError::HandshakeRequestError)
}
}
}
}
|