Skip to content

service.cpp: Refactored service code #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions includeos/service.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,18 @@
// See the License for the specific language governing permissions and
// limitations under the License.

#include <net/http/server.hpp>
#include <net/inet4>
#include <net/ws/websocket.hpp>
#include <service>

static std::map<int, net::WebSocket_ptr> websockets;
static int idx = 0;
using WebSocket_pool_index = int;
using WebSocket_pool = std::map<WebSocket_pool_index, net::WebSocket_ptr>;

static http::Server_ptr server;

static WebSocket_pool_index idx;
static WebSocket_pool websockets;

void print_num_clients()
{
Expand All @@ -29,9 +35,9 @@ void print_num_clients()

void handle_ws(net::WebSocket_ptr ws)
{
// nullptr means the WS attempt failed
// nullptr means the WebSocket attempt failed
if(not ws) {
printf("WS failed\n");
printf("WebSocket connection failed\n");
return;
}
//printf("WS Connected: %s\n", ws->to_string().c_str());
Expand All @@ -51,28 +57,25 @@ void handle_ws(net::WebSocket_ptr ws)
idx++;
}

#include <net/http/server.hpp>
std::unique_ptr<http::Server> server;

void Service::start()
{
// Retreive the stack (configured from outside)
auto& inet = net::Inet4::stack<0>();
Expects(inet.is_configured());

// Create a HTTP Server and setup request handling
server = std::make_unique<http::Server>(inet.tcp());
server = http::make_server(inet.tcp());
server->on_request([] (auto req, auto rw)
{
// We only support get
if(req->method() != http::GET) {
rw->write_header(http::Not_Found);
return;
}

// WebSockets go here
if(req->uri() == "/") {
auto ws = net::WebSocket::upgrade(*req, *rw);
handle_ws(std::move(ws));
handle_ws(net::WebSocket::upgrade(*req, *rw));
}
else {
rw->write_header(http::Not_Found);
Expand All @@ -82,8 +85,8 @@ void Service::start()
// Start listening on port 80
server->listen(80);

Timers::periodic(1s, 1s,
[&inet] (uint32_t) {
print_num_clients();
});
// Periodically print number of connected clients
Timers::periodic(1s, 1s, [](uint32_t){
print_num_clients();
});
}