#include #include #include #include #include "websockets.h" #include "json.h" #include "json_ext.h" #include "basics.h" #include "app.h" std::unique_ptr app; using namespace websockets; websockets::TestProtocol default_protocol{ // connection established [](User& user, basic_websocket_info){ app->login(user); std::cout << "New user!\n"; }, // connection closed [](User& user, basic_websocket_info){ app->logout(user); std::cout << "User left: " << &user << ": " << user.name << std::endl; }, // write (will always come after receive) [](User& user, basic_websocket_info) -> std::string{ js::Object ret; if(user.update_lines){ ret["lines"] = vector_to_json(app->lines, [](AbstractLine const & l){return cheap_line_type(l);}); user.update_lines = false; } else { ret["balls"] = vector_to_json(app->sim.balls, [](ball_type const & b){return cheap_ball_type(b);}); } return write_json(ret); }, // receive [](User& user, std::string in, basic_websocket_info){ try{ auto object = parse_json(in).getObject(); auto command = object["command"]; if(command == "add line"){ app->add_line(from_json(object["data"])); std::cout << "Line from: " << &user << ": " << user.name << std::endl; } else if (command == "update user") { user = from_json(object["data"]); std::cout << "Updated user: " << &user << ": " << user.name << std::endl; } } catch(std::exception& e) { throw websockets::runtime_error(e.what()); } } }; websockets::TestProtocol observer_protocol{ // connection established [](Empty& user, basic_websocket_info){}, // connection closed [](Empty& user, basic_websocket_info){}, // write (will always come after receive) [](Empty& user, basic_websocket_info) -> std::string{ js::Object ret; ret["people"] = vector_to_json(app->people_online, [](User* u){return *u;}); ret["balls"] = vector_to_json(app->sim.balls); ret["lines"] = vector_to_json(app->sim.lines); return write_json(ret); }, // receive [](Empty& user, std::string in, basic_websocket_info){} }; websockets::TestProtocol uberclient_protocol{ // connection established [](Empty& user, basic_websocket_info binfo){ if(app->uberclient) throw websockets::runtime_error("Warning: another uberclient connection\n"); app->uberclient = binfo.wsi; }, // connection closed [](Empty& user, basic_websocket_info){ app->uberclient = nullptr; }, // write (will always come after receive) [](Empty& user, basic_websocket_info) -> std::string{ static int i = 0; return std::to_string(i++); }, // receive [](Empty& user, std::string in, basic_websocket_info){} }; int main(int argc, char **argv){ app.reset(new App); libwebsocket_protocols protocols[] = { WSstandard_protocol("default", default_protocol), WSstandard_protocol("observer", observer_protocol), WSstandard_protocol("uberclient", uberclient_protocol), { NULL, NULL, 0 } // end of list }; return websockets::default_main(argc, argv, protocols, []{app->update();}); }