From 6d988d13f7fc1652e2d041cfd1c4b40dce6a8adb Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Tue, 7 May 2019 05:30:03 +0200 Subject: Add the game server --- game_server/Cargo.toml | 9 +++++++++ game_server/build.sh | 3 +++ game_server/src/main.rs | 3 +++ 3 files changed, 15 insertions(+) create mode 100644 game_server/Cargo.toml create mode 100755 game_server/build.sh create mode 100644 game_server/src/main.rs (limited to 'game_server') diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml new file mode 100644 index 0000000..fba755c --- /dev/null +++ b/game_server/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "game-server" +version = "0.1.0" +authors = ["natrixaeria", "truedoctor"] +edition = "2018" +description = "A general game server for connections to web clients. Currently (on the way to) deploying a skribbl.io like game." + +[dependencies] +rocket = "0.4" diff --git a/game_server/build.sh b/game_server/build.sh new file mode 100755 index 0000000..67e239f --- /dev/null +++ b/game_server/build.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +rustup run nightly cargo run diff --git a/game_server/src/main.rs b/game_server/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/game_server/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} -- cgit v1.2.3-54-g00ecf From e2d83e09f8af95c82385967f61e2ec8342a4b2c9 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Tue, 7 May 2019 05:51:58 +0200 Subject: Add a logging feature with pretty_env_logger --- game_server/Cargo.toml | 2 ++ game_server/build.sh | 3 ++- game_server/src/group.rs | 7 +++++++ game_server/src/lobby.rs | 2 ++ game_server/src/main.rs | 10 +++++++++- 5 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 game_server/src/group.rs create mode 100644 game_server/src/lobby.rs (limited to 'game_server') diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml index fba755c..f3aabed 100644 --- a/game_server/Cargo.toml +++ b/game_server/Cargo.toml @@ -6,4 +6,6 @@ edition = "2018" description = "A general game server for connections to web clients. Currently (on the way to) deploying a skribbl.io like game." [dependencies] +log = "0.4" +pretty_env_logger = "0.3" rocket = "0.4" diff --git a/game_server/build.sh b/game_server/build.sh index 67e239f..9def83e 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -1,3 +1,4 @@ #!/usr/bin/env sh -rustup run nightly cargo run +rustup run nightly cargo build +RUST_LOG=trace target/debug/game-server diff --git a/game_server/src/group.rs b/game_server/src/group.rs new file mode 100644 index 0000000..3241eee --- /dev/null +++ b/game_server/src/group.rs @@ -0,0 +1,7 @@ +struct Group { + id: u32, + name: String, +} + +impl Group { +} diff --git a/game_server/src/lobby.rs b/game_server/src/lobby.rs new file mode 100644 index 0000000..c0717d3 --- /dev/null +++ b/game_server/src/lobby.rs @@ -0,0 +1,2 @@ +struct Lobby { +} diff --git a/game_server/src/main.rs b/game_server/src/main.rs index e7a11a9..685c633 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,3 +1,11 @@ +mod lobby; +mod group; + +#[macro_use] extern crate log; +use pretty_env_logger; + fn main() { - println!("Hello, world!"); + pretty_env_logger::init(); + + trace!("test info"); } -- cgit v1.2.3-54-g00ecf From 73eb78e3ac5eb7d382c1aca98da84cd866d54570 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Sat, 11 May 2019 06:26:26 +0200 Subject: Create a fundamental project structure --- game_server/build.sh | 8 ++++++-- game_server/src/group.rs | 19 +++++++++++++++++-- game_server/src/lobby.rs | 35 ++++++++++++++++++++++++++++++++++- game_server/src/main.rs | 15 +++++++++++++-- 4 files changed, 70 insertions(+), 7 deletions(-) (limited to 'game_server') diff --git a/game_server/build.sh b/game_server/build.sh index 9def83e..c42a7ac 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -1,4 +1,8 @@ #!/usr/bin/env sh -rustup run nightly cargo build -RUST_LOG=trace target/debug/game-server +if rustup run nightly cargo build; then + echo build success! + RUST_LOG=trace target/debug/game-server +else + echo build failed! +fi diff --git a/game_server/src/group.rs b/game_server/src/group.rs index 3241eee..9774979 100644 --- a/game_server/src/group.rs +++ b/game_server/src/group.rs @@ -1,7 +1,22 @@ -struct Group { - id: u32, +pub type GroupId = u32; + +pub struct Group { + id: GroupId, name: String, } impl Group { + pub(crate) fn new(id: GroupId, name: String) -> Group { + Group { id, name } + } + + pub(crate) fn get_id(&self) -> GroupId { + self.id + } + + pub fn run(&self) { + let id = self.id; + std::thread::spawn(move || + loop {println!("group id: {} meldet sich", id)}); + } } diff --git a/game_server/src/lobby.rs b/game_server/src/lobby.rs index c0717d3..8808b7f 100644 --- a/game_server/src/lobby.rs +++ b/game_server/src/lobby.rs @@ -1,2 +1,35 @@ -struct Lobby { +use std::collections::HashMap; + +use super::group::{Group, GroupId}; + +pub struct Lobby { + groups: HashMap, +} + +impl Lobby { + pub fn new() -> Lobby { + Self { + groups: HashMap::new(), + } + } + + pub fn add_group(&mut self, group: Group) { + self.groups.insert(group.get_id(), group); + } + + pub fn iter<'a>(&'a self) -> GroupIterator<'a> { + GroupIterator { groups: self.groups.values() } + } +} + +pub struct GroupIterator<'a> { + groups: std::collections::hash_map::Values<'a, GroupId, Group> +} + +impl<'a> Iterator for GroupIterator<'a> { + type Item = &'a Group; + + fn next(&mut self) -> Option { + self.groups.next() + } } diff --git a/game_server/src/main.rs b/game_server/src/main.rs index 685c633..7e08b46 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,11 +1,22 @@ -mod lobby; mod group; +mod lobby; #[macro_use] extern crate log; use pretty_env_logger; +use group::Group; +use lobby::Lobby; + fn main() { pretty_env_logger::init(); - trace!("test info"); + let mut lobby = Lobby::new(); + lobby.add_group(Group::new(0, "Test".to_string())); + lobby.add_group(Group::new(1, "Very Serious".to_string())); + + for group in lobby.iter() { + group.run() + } + + loop {} } -- cgit v1.2.3-54-g00ecf From 2f9e5dfaac05538fdf4513569b4df6872ee85b89 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Wed, 15 May 2019 23:46:11 +0200 Subject: Add web client functionality additionally added -r feature to build.sh, which reverses build output. --- game_server/Cargo.toml | 3 +- game_server/build.sh | 25 +++++++++--- game_server/err | 73 +++++++++++++++++++++++++++++++++++ game_server/rbuild.sh | 2 + game_server/src/backend_connection.rs | 31 +++++++++++++++ game_server/src/gameserver.rs | 0 game_server/src/group.rs | 22 ++--------- game_server/src/lobby.rs | 10 ++--- game_server/src/main.rs | 13 +++++-- game_server/src/test_group.rs | 28 ++++++++++++++ 10 files changed, 173 insertions(+), 34 deletions(-) create mode 100644 game_server/err create mode 100644 game_server/rbuild.sh create mode 100644 game_server/src/backend_connection.rs create mode 100644 game_server/src/gameserver.rs create mode 100644 game_server/src/test_group.rs (limited to 'game_server') diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml index f3aabed..baf27fa 100644 --- a/game_server/Cargo.toml +++ b/game_server/Cargo.toml @@ -8,4 +8,5 @@ description = "A general game server for connections to web clients. Currently ( [dependencies] log = "0.4" pretty_env_logger = "0.3" -rocket = "0.4" +reqwest = "0.9" +websocket = "0.22" diff --git a/game_server/build.sh b/game_server/build.sh index c42a7ac..5929e29 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -1,8 +1,21 @@ #!/usr/bin/env sh -if rustup run nightly cargo build; then - echo build success! - RUST_LOG=trace target/debug/game-server -else - echo build failed! -fi +case $1 in + ("") + if rustup run nightly cargo --color always build; then + echo build success! + RUST_LOG=info target/debug/game-server + else + echo build failed! + fi + ;; + -r) + sh build.sh &> err && cat err | tac + ;; + -c) + rustup run nightly cargo clean + ;; + *) + echo invalid argument + ;; +esac diff --git a/game_server/err b/game_server/err new file mode 100644 index 0000000..6ca8a6f --- /dev/null +++ b/game_server/err @@ -0,0 +1,73 @@ + Compiling game-server v0.1.0 (/home/jan/projects/DiscoBot/game_server) +error[E0277]: the trait bound `(): futures::future::Future` is not satisfied + --> src/backend_connection.rs:32:24 + | +32 |  hyper::rt::run(hyper::rt::lazy(|| { + |  ^^^^^^^^^^^^^^^ the trait `futures::future::Future` is not implemented for `()` + | + = note: required because of the requirements on the impl of `futures::future::IntoFuture` for `()` + = note: required by `futures::future::lazy::lazy` + +error[E0599]: no method named `wait` found for type `std::result::Result, [closure@src/backend_connection.rs:55:38: 55:73]>, http::uri::InvalidUri>` in the current scope + --> src/backend_connection.rs:56:24 + | +56 |  }).wait(); + |  ^^^^ + | + = note: the method `wait` exists but the following trait bounds were not satisfied: + `&mut std::result::Result, [closure@src/backend_connection.rs:55:38: 55:73]>, http::uri::InvalidUri> : futures::future::Future` + +error[E0308]: mismatched types + --> src/backend_connection.rs:58:17 + | +58 |  res + |  ^^^ expected (), found enum `std::result::Result` + | + = note: expected type `()` + found type `std::result::Result, http::uri::InvalidUri>` + +error[E0277]: the trait bound `(): futures::future::Future` is not satisfied + --> src/backend_connection.rs:32:24 + | +32 |   hyper::rt::run(hyper::rt::lazy(|| { + |  ________________________^ +33 | |  let client = hyper::Client::builder() +34 | |  .build::<_, hyper::Body>( +35 | |  HttpsConnector::new(4).unwrap() +... | +59 | |  } +60 | |  })); + | |__________^ the trait `futures::future::Future` is not implemented for `()` + | + = note: required because of the requirements on the impl of `futures::future::IntoFuture` for `()` + = note: required by `futures::future::lazy::Lazy` + +error[E0277]: the trait bound `(): futures::future::Future` is not satisfied + --> src/backend_connection.rs:32:9 + | +32 |  hyper::rt::run(hyper::rt::lazy(|| { + |  ^^^^^^^^^^^^^^ the trait `futures::future::Future` is not implemented for `()` + | + = note: required because of the requirements on the impl of `futures::future::IntoFuture` for `()` + = note: required by `hyper::rt::run` + +error[E0063]: missing field `res_receiver` in initializer of `backend_connection::BackendConnection` + --> src/backend_connection.rs:62:9 + | +62 |  BackendConnection { + |  ^^^^^^^^^^^^^^^^^ missing `res_receiver` + +error[E0609]: no field `request_sender` on type `&backend_connection::BackendConnection` + --> src/backend_connection.rs:69:14 + | +69 |  self.request_sender.send( + |  ^^^^^^^^^^^^^^ + +error: aborting due to 7 previous errors + +Some errors have detailed explanations: E0063, E0277, E0308, E0599, E0609. +For more information about an error, try `rustc --explain E0063`. +error: Could not compile `game-server`. + +To learn more, run the command again with --verbose. +build failed! diff --git a/game_server/rbuild.sh b/game_server/rbuild.sh new file mode 100644 index 0000000..22b10b5 --- /dev/null +++ b/game_server/rbuild.sh @@ -0,0 +1,2 @@ +#!/bin/bash +sh build.sh &> err && cat err | tac diff --git a/game_server/src/backend_connection.rs b/game_server/src/backend_connection.rs new file mode 100644 index 0000000..9307c4a --- /dev/null +++ b/game_server/src/backend_connection.rs @@ -0,0 +1,31 @@ +use reqwest::{Response, Client, Url, UrlError, Error as ReqError}; + +pub struct BackendConnection { + host: String, + client: Client, + last_response: Option> +} + +impl BackendConnection { + pub fn new(host: &str) -> Self { + BackendConnection { + host: host.to_string(), + client: Client::new(), + last_response: None + } + } + + pub fn request(&mut self, location: &str) -> Result<(), UrlError> { + Ok(self.last_response = + Some(self.client.get(Url::parse(&format!("{}{}", self.host, location))?) + .send())) + } + + pub fn get_response(&self) -> &Option> { + &self.last_response + } + + pub fn host_name<'a>(&'a self) -> &'a str { + &self.host + } +} diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs new file mode 100644 index 0000000..e69de29 diff --git a/game_server/src/group.rs b/game_server/src/group.rs index 9774979..55e4fbf 100644 --- a/game_server/src/group.rs +++ b/game_server/src/group.rs @@ -1,22 +1,8 @@ pub type GroupId = u32; -pub struct Group { - id: GroupId, - name: String, -} - -impl Group { - pub(crate) fn new(id: GroupId, name: String) -> Group { - Group { id, name } - } - - pub(crate) fn get_id(&self) -> GroupId { - self.id - } +pub trait Group { + fn id(&self) -> GroupId; + fn name(&self) -> String; - pub fn run(&self) { - let id = self.id; - std::thread::spawn(move || - loop {println!("group id: {} meldet sich", id)}); - } + fn run(&self); } diff --git a/game_server/src/lobby.rs b/game_server/src/lobby.rs index 8808b7f..fe3bdee 100644 --- a/game_server/src/lobby.rs +++ b/game_server/src/lobby.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use super::group::{Group, GroupId}; pub struct Lobby { - groups: HashMap, + groups: HashMap>, } impl Lobby { @@ -13,8 +13,8 @@ impl Lobby { } } - pub fn add_group(&mut self, group: Group) { - self.groups.insert(group.get_id(), group); + pub fn add_group(&mut self, group: Box) { + self.groups.insert(group.id(), group); } pub fn iter<'a>(&'a self) -> GroupIterator<'a> { @@ -23,11 +23,11 @@ impl Lobby { } pub struct GroupIterator<'a> { - groups: std::collections::hash_map::Values<'a, GroupId, Group> + groups: std::collections::hash_map::Values<'a, GroupId, Box> } impl<'a> Iterator for GroupIterator<'a> { - type Item = &'a Group; + type Item = &'a Box; fn next(&mut self) -> Option { self.groups.next() diff --git a/game_server/src/main.rs b/game_server/src/main.rs index 7e08b46..f7a1085 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,22 +1,27 @@ mod group; +mod test_group; mod lobby; +mod backend_connection; #[macro_use] extern crate log; use pretty_env_logger; -use group::Group; +use test_group::TestGroup; use lobby::Lobby; +use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); let mut lobby = Lobby::new(); - lobby.add_group(Group::new(0, "Test".to_string())); - lobby.add_group(Group::new(1, "Very Serious".to_string())); for group in lobby.iter() { group.run() } - loop {} + let mut backend = BackendConnection::new("http://129.13.215.68:5000"); + loop { + backend.request("/scribble").unwrap(); + println!("{:?}", backend.get_response()); + } } diff --git a/game_server/src/test_group.rs b/game_server/src/test_group.rs new file mode 100644 index 0000000..bd570e3 --- /dev/null +++ b/game_server/src/test_group.rs @@ -0,0 +1,28 @@ +use super::group::{Group, GroupId}; + +pub struct TestGroup { + id: GroupId, + name: String, +} + +impl Group for TestGroup { + fn id(&self) -> GroupId { + self.id + } + + fn name(&self) -> String { + self.name.clone() + } + + fn run(&self) { + let id = self.id; + let name = self.name.to_owned(); + std::thread::spawn(move || /*loop { println!("> group nr.{} wishes you: '{}'", id, name) }*/()); + } +} + +impl TestGroup { + pub fn new(id: GroupId, name: String) -> Self { + TestGroup { id, name } + } +} -- cgit v1.2.3-54-g00ecf From 921d023a7652be5b1232ac41aeb2646b5f83ceb5 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Fri, 17 May 2019 20:59:10 +0200 Subject: Add WebSocket server functionality and a WebSocket javascript test suite --- game_server/build.sh | 6 ++-- game_server/src/gameserver.rs | 44 +++++++++++++++++++++++++++++ game_server/src/main.rs | 14 +++++++--- game_server/src/ws_test.html | 65 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 122 insertions(+), 7 deletions(-) create mode 100644 game_server/src/ws_test.html (limited to 'game_server') diff --git a/game_server/build.sh b/game_server/build.sh index 5929e29..1eb61a1 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -2,9 +2,9 @@ case $1 in ("") - if rustup run nightly cargo --color always build; then + if rustup run stable cargo --color always build; then echo build success! - RUST_LOG=info target/debug/game-server + RUST_LOG=debug target/debug/game-server else echo build failed! fi @@ -13,7 +13,7 @@ case $1 in sh build.sh &> err && cat err | tac ;; -c) - rustup run nightly cargo clean + rustup run stable cargo clean ;; *) echo invalid argument diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs index e69de29..6bc3e07 100644 --- a/game_server/src/gameserver.rs +++ b/game_server/src/gameserver.rs @@ -0,0 +1,44 @@ +use websocket::{OwnedMessage, sync::Server, server::NoTlsAcceptor}; +use std::net::{SocketAddr, ToSocketAddrs}; +use std::sync::mpsc; +use std::sync::mpsc::{Sender, Receiver}; + +#[derive(Debug)] +pub enum GameServerError { + BindError(std::io::Error), +} + +type ClientConnection = Result<(), GameServerError>; + +pub struct GameServer { + addr: SocketAddr, + rec: Receiver, +} + +impl GameServer { + pub fn new(addr: T) -> Self { + let (s, r): (Sender, Receiver) + = mpsc::channel(); + let addr = addr.to_socket_addrs().unwrap().next().unwrap(); + debug!("ws address: {}", addr); + std::thread::spawn(move || { + let server = match Server::::bind(addr) { + Ok(v) => v, + Err(e) => { + s.send(Err(GameServerError::BindError(e))).unwrap(); + return; + }, + }; + info!("webserver is being launched"); + for req in server { + //println!("{:?}", req); + println!("gotcha"); + } + info!("webserver is being shut down"); + }); + GameServer { + addr, + rec: r, + } + } +} diff --git a/game_server/src/main.rs b/game_server/src/main.rs index f7a1085..2d261d8 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,27 +1,33 @@ mod group; mod test_group; mod lobby; +mod gameserver; mod backend_connection; #[macro_use] extern crate log; use pretty_env_logger; -use test_group::TestGroup; use lobby::Lobby; use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); + info!("create lobby"); let mut lobby = Lobby::new(); + let addr = ("127.0.0.1", 5001); + info!("create game server on {:?}", addr); + let gameserver = gameserver::GameServer::new(addr); for group in lobby.iter() { group.run() } - let mut backend = BackendConnection::new("http://129.13.215.68:5000"); + let mut backend = BackendConnection::new("https://kobert.dev"); loop { - backend.request("/scribble").unwrap(); - println!("{:?}", backend.get_response()); + std::thread::sleep(std::time::Duration::from_millis(1000)); + + //backend.request("/api/lobby/tokens/1230").unwrap(); + //println!("{:?}", backend.get_response()); } } diff --git a/game_server/src/ws_test.html b/game_server/src/ws_test.html new file mode 100644 index 0000000..29d4d50 --- /dev/null +++ b/game_server/src/ws_test.html @@ -0,0 +1,65 @@ + + + + WS Test + + + +
connected

+
+ Server address: +
+ + + -- cgit v1.2.3-54-g00ecf From 70f46161fe0c9819d463cf612d60d4c03faabe7e Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Sat, 18 May 2019 05:27:06 +0200 Subject: Add threading and possibility to connect to socket --- game_server/Cargo.toml | 1 + game_server/src/gameserver.rs | 148 +++++++++++++++++++++++++++++++++++------- game_server/src/main.rs | 17 +---- game_server/src/ws_test.html | 5 +- 4 files changed, 131 insertions(+), 40 deletions(-) (limited to 'game_server') diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml index baf27fa..97c0e77 100644 --- a/game_server/Cargo.toml +++ b/game_server/Cargo.toml @@ -10,3 +10,4 @@ log = "0.4" pretty_env_logger = "0.3" reqwest = "0.9" websocket = "0.22" +hyper = "0.10" diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs index 6bc3e07..377654e 100644 --- a/game_server/src/gameserver.rs +++ b/game_server/src/gameserver.rs @@ -1,44 +1,146 @@ -use websocket::{OwnedMessage, sync::Server, server::NoTlsAcceptor}; -use std::net::{SocketAddr, ToSocketAddrs}; +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) } -type ClientConnection = Result<(), GameServerError>; - pub struct GameServer { addr: SocketAddr, - rec: Receiver, + lobby: Lobby, + backend: BackendConnection, +} + +pub struct GameClient { + addr: SocketAddr, + client: Client, +} + +impl GameClient { + fn from_raw(client: Client) -> Result { + let addr = client.peer_addr().map_err(|_| ())?; + info!("got a client connection from: {}", addr); + Ok(GameClient { + addr, + client, + }) + } + + fn require_token(&mut self) -> Option { + let message = self.client + .recv_message() + .ok()?; + if let OwnedMessage::Text(text) = message { + text.parse::().ok() + } else { + None + } + } } +type ClientConnection = Result; + impl GameServer { pub fn new(addr: T) -> Self { - let (s, r): (Sender, Receiver) - = mpsc::channel(); let addr = addr.to_socket_addrs().unwrap().next().unwrap(); debug!("ws address: {}", addr); - std::thread::spawn(move || { - let server = match Server::::bind(addr) { - Ok(v) => v, - Err(e) => { - s.send(Err(GameServerError::BindError(e))).unwrap(); - return; - }, - }; - info!("webserver is being launched"); - for req in server { - //println!("{:?}", req); - println!("gotcha"); - } - info!("webserver is being shut down"); - }); + info!("create lobby"); + let lobby = Lobby::new(); + let backend = BackendConnection::new("https://kobert.dev"); + info!("got a C# backend connection"); GameServer { addr, - rec: r, + 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()); + }); + } + + fn read_clients(&self) -> Receiver { + let (s, r): (Sender, Receiver) + = 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) -> Result<(), GameServerError> { + let server = match Server::::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) -> 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) + } } } } diff --git a/game_server/src/main.rs b/game_server/src/main.rs index 2d261d8..d8a7b53 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -7,27 +7,14 @@ mod backend_connection; #[macro_use] extern crate log; use pretty_env_logger; -use lobby::Lobby; use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); - info!("create lobby"); - let mut lobby = Lobby::new(); - let addr = ("127.0.0.1", 5001); + let addr = ("0.0.0.0", 5001); info!("create game server on {:?}", addr); let gameserver = gameserver::GameServer::new(addr); + gameserver.run().unwrap(); - for group in lobby.iter() { - group.run() - } - - let mut backend = BackendConnection::new("https://kobert.dev"); - loop { - std::thread::sleep(std::time::Duration::from_millis(1000)); - - //backend.request("/api/lobby/tokens/1230").unwrap(); - //println!("{:?}", backend.get_response()); - } } diff --git a/game_server/src/ws_test.html b/game_server/src/ws_test.html index 29d4d50..ea259b7 100644 --- a/game_server/src/ws_test.html +++ b/game_server/src/ws_test.html @@ -22,10 +22,11 @@ function get_addr() { function test_connection() { let a = 'ws://' + get_addr(); add_text('create a new connection at "' + a + '"'); - const ws = new WebSocket(a); + const ws = new WebSocket(a, 'tuesday'); ws.addEventListener('open', function (event) { add_text('connection established'); toggle_connected(true); + ws.send('1230123'); }); ws.addEventListener('error', function (event) { add_text('ws error occured: "' + event + '"'); @@ -36,7 +37,7 @@ function test_connection() { toggle_connected(false); }); ws.addEventListener('message', function (event) { - add_text('got ws message: ' + event); + add_text('got ws message: ' + event.data); }); } -- cgit v1.2.3-54-g00ecf From f3983341be939235c1a6cd522b3bb5cc318a6d1a Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Sat, 18 May 2019 05:52:08 +0200 Subject: Keep client connections open and start the server on localhost --- game_server/src/gameserver.rs | 1 + game_server/src/main.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'game_server') diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs index 377654e..9334a27 100644 --- a/game_server/src/gameserver.rs +++ b/game_server/src/gameserver.rs @@ -83,6 +83,7 @@ impl GameServer { 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)); } }); } diff --git a/game_server/src/main.rs b/game_server/src/main.rs index d8a7b53..e129283 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -12,7 +12,7 @@ use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); - let addr = ("0.0.0.0", 5001); + let addr = ("127.0.0.1", 5001); info!("create game server on {:?}", addr); let gameserver = gameserver::GameServer::new(addr); gameserver.run().unwrap(); -- cgit v1.2.3-54-g00ecf