~starkingdoms/starkingdoms

ref: eb564a785cf444554678a90860be0c43b296313f starkingdoms/server/src/ws.rs -rw-r--r-- 8.7 KiB
eb564a78 — core fmt 1 year, 8 months ago
                                                                                
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// StarKingdoms.IO, a browser game about drifting through space
//     Copyright (C) 2024 ghostly_zsh, TerraMaster85, core
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU Affero General Public License as published by
//     the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU Affero General Public License for more details.
//
//     You should have received a copy of the GNU Affero General Public License
//     along with this program.  If not, see <https://www.gnu.org/licenses/>.

use bevy::app::{App, Plugin, PostUpdate, Startup};
use bevy::ecs::event::ManualEventReader;
use bevy::log::{error, warn};
use bevy::prelude::{Commands, Event, Events, Local, Res, ResMut, Resource};
use crossbeam_channel::{unbounded, Receiver};
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr, TcpListener};
use std::sync::{Arc, RwLock};
use std::thread;

use tungstenite::protocol::Role;
use tungstenite::{Message, WebSocket};

pub use tungstenite;

pub struct StkTungsteniteServerPlugin;

impl Plugin for StkTungsteniteServerPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<WsEvent>();
        app.add_systems(Startup, Self::init_server);
        app.add_systems(PostUpdate, Self::event_listener);
    }
}

#[derive(Event, Clone, Debug)]
pub enum WsEvent {
    Connection { from: SocketAddr },
    Close { addr: SocketAddr },
    Send { to: SocketAddr, message: Message },
    Recv { from: SocketAddr, message: Message },
    Broadcast { message: Message },
}

#[derive(Resource, Clone)]
pub struct Clients(Arc<RwLock<HashMap<SocketAddr, std::sync::mpsc::Sender<WsEvent>>>>);

#[derive(Resource)]
pub struct StkTungsteniteServerConfig {
    pub addr: IpAddr,
    pub port: u16,
}

#[derive(Resource)]
pub struct Rx<A>(Receiver<A>);

//#[derive(Resource)]
//pub struct Tx<A>(Sender<A>);

impl StkTungsteniteServerPlugin {
    pub fn init_server(config: Res<StkTungsteniteServerConfig>, mut commands: Commands) {
        let listener = TcpListener::bind(SocketAddr::from((config.addr, config.port)))
            .expect("Failed to bind");

        let (tx, rx) = unbounded::<WsEvent>();

        let clients = Clients(Arc::new(RwLock::new(HashMap::new())));

        commands.insert_resource(clients.clone());
        commands.insert_resource(Rx(rx.clone()));
        //commands.insert_resource(Tx(tx.clone()));

        let clients = clients.0.clone();

        thread::spawn(move || {
            loop {
                let (stream, this_addr) = listener.accept().unwrap();

                let upgraded = match tungstenite::accept(stream) {
                    Ok(up) => up,
                    Err(e) => {
                        warn!("error upgrading {}: {}", this_addr, e);
                        continue;
                    }
                };

                let (ltx, lrx) = std::sync::mpsc::channel();

                {
                    // Lock block
                    let mut handle = clients.write().expect("failed to lock clients map");
                    handle.insert(this_addr, ltx);
                } // unlocked here

                tx.send(WsEvent::Connection { from: this_addr })
                    .expect("failed to send event across channel");

                // send packet
                thread::spawn({
                    let fd_ref = upgraded
                        .get_ref()
                        .try_clone()
                        .expect("failed to clone tcpstream");
                    let mut l_stream = WebSocket::from_raw_socket(fd_ref, Role::Server, None);
                    let l_gtx = tx.clone();
                    move || {
                        for event in lrx.iter() {
                            match event {
                                WsEvent::Send { to, message } => {
                                    if to == this_addr {
                                        match l_stream.send(message) {
                                            Ok(_) => (),
                                            Err(e) => match e {
                                                tungstenite::Error::AlreadyClosed
                                                | tungstenite::Error::ConnectionClosed => {
                                                    l_gtx
                                                        .send(WsEvent::Close { addr: this_addr })
                                                        .expect("failed to send on stream");
                                                }
                                                e => {
                                                    error!("error sending to {}: {}", this_addr, e);
                                                    break;
                                                }
                                            },
                                        }
                                    }
                                }
                                WsEvent::Close { addr } => {
                                    if addr == this_addr {
                                        match l_stream.close(None) {
                                            Ok(_) => (),
                                            Err(e) => {
                                                error!("failed to disconnect client: {}", e);
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                });

                // receive packet
                thread::spawn({
                    let fd_ref = upgraded
                        .get_ref()
                        .try_clone()
                        .expect("failed to clone tcpstream");
                    let mut l_stream = WebSocket::from_raw_socket(fd_ref, Role::Server, None);
                    let l_gtx = tx.clone();
                    move || loop {
                        let msg = match l_stream.read() {
                            Ok(m) => m,
                            Err(e) => {
                                error!("error reading from stream: {}", e);
                                break;
                            }
                        };
                        if let Message::Close(_) = msg {
                            let _ = l_stream.close(None);
                            l_gtx.send(WsEvent::Close { addr: this_addr }).unwrap();
                            break;
                        }
                        l_gtx
                            .send(WsEvent::Recv {
                                from: this_addr,
                                message: msg,
                            })
                            .unwrap();
                    }
                });
            }
        });
    }

    pub fn event_listener(
        clients: Res<Clients>,
        game_receiver: Res<Rx<WsEvent>>,
        mut event_reader: Local<ManualEventReader<WsEvent>>,
        mut events: ResMut<Events<WsEvent>>,
    ) {
        let mut clients = clients.0.write().unwrap();
        for event in event_reader.read(&events) {
            match event {
                WsEvent::Send { to, .. } => {
                    if let Some(client) = clients.get_mut(to) {
                        client.send(event.clone()).expect("failed to forward event");
                    }
                }
                WsEvent::Close { addr } => {
                    if let Some(client) = clients.get_mut(addr) {
                        match client.send(event.clone()) {
                            Ok(_) => (),
                            Err(e) => error!("failed to forward event: {}", e),
                        }
                    }
                    clients.remove(addr);
                }
                WsEvent::Broadcast { message } => {
                    for (addr, client) in clients.iter() {
                        client
                            .send(WsEvent::Send {
                                to: *addr,
                                message: message.clone(),
                            })
                            .expect("failed to forward event");
                    }
                }
                _ => {}
            }
        }

        if let Ok(event) = game_receiver.0.try_recv() {
            events.send(event);
        }
    }
}