move to new skeleton

This commit is contained in:
Sergio R. Caprile committed 2024-04-26 16:58:58 -03:00
1 parent 972b255a48
commit 663c645cf1
25 files changed
+9 -9

No files matched your search

@@ -0,0 +1,25 @@
PROG ?= example # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
SOURCES = main.c mongoose.c # Source code files
CFLAGS = -W -Wall -Wextra -g -I. # Build options
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
#CFLAGS_MONGOOSE += -DMG_ENABLE_LINES
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= example.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
endif
all: $(PROG) # Default target. Build and run program
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM
@@ -0,0 +1 @@
See detailed tutorial at https://mongoose.ws/tutorials/websocket/json-rpc-over-websocket/
@@ -0,0 +1,84 @@
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// See https://mongoose.ws/tutorials/json-rpc-over-websocket/
#include "mongoose.h"
static const char *s_listen_on = "ws://localhost:8000";
static const char *s_web_root = "web_root";
static struct mg_rpc *s_rpc_head = NULL;
static void rpc_sum(struct mg_rpc_req *r) {
double a = 0.0, b = 0.0;
mg_json_get_num(r->frame, "$.params[0]", &a);
mg_json_get_num(r->frame, "$.params[1]", &b);
mg_rpc_ok(r, "%g", a + b);
}
static void rpc_mul(struct mg_rpc_req *r) {
double a = 0.0, b = 0.0;
mg_json_get_num(r->frame, "$.params[0]", &a);
mg_json_get_num(r->frame, "$.params[1]", &b);
mg_rpc_ok(r, "%g", a * b);
}
// This RESTful server implements the following endpoints:
// /websocket - upgrade to Websocket, and implement websocket echo server
// any other URI serves static files from s_web_root
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_OPEN) {
// c->is_hexdumping = 1;
} else if (ev == MG_EV_WS_OPEN) {
c->data[0] = 'W'; // Mark this connection as an established WS client
} else if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/websocket"), NULL)) {
// Upgrade to websocket. From now on, a connection is a full-duplex
// Websocket connection, which will receive MG_EV_WS_MSG events.
mg_ws_upgrade(c, hm, NULL);
} else {
// Serve static files
struct mg_http_serve_opts opts = {.root_dir = s_web_root};
mg_http_serve_dir(c, ev_data, &opts);
}
} else if (ev == MG_EV_WS_MSG) {
// Got websocket frame. Received data is wm->data
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
struct mg_iobuf io = {0, 0, 0, 512};
struct mg_rpc_req r = {&s_rpc_head, 0, mg_pfn_iobuf, &io, 0, wm->data};
mg_rpc_process(&r);
if (io.buf) mg_ws_send(c, (char *) io.buf, io.len, WEBSOCKET_OP_TEXT);
mg_iobuf_free(&io);
}
}
static void timer_fn(void *arg) {
struct mg_mgr *mgr = (struct mg_mgr *) arg;
// Broadcast message to all connected websocket clients.
for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
if (c->data[0] != 'W') continue;
mg_ws_printf(c, WEBSOCKET_OP_TEXT, "{%m:%m,%m:[%d,%d,%d]}",
MG_ESC("method"), MG_ESC("notification1"), MG_ESC("params"), 1,
2, 3);
}
}
int main(void) {
struct mg_mgr mgr; // Event manager
mg_mgr_init(&mgr); // Init event manager
mg_log_set(MG_LL_DEBUG); // Set log level
mg_timer_add(&mgr, 5000, MG_TIMER_REPEAT, timer_fn, &mgr); // Init timer
// Configure JSON-RPC functions we're going to handle
mg_rpc_add(&s_rpc_head, mg_str("sum"), rpc_sum, NULL);
mg_rpc_add(&s_rpc_head, mg_str("mul"), rpc_mul, NULL);
mg_rpc_add(&s_rpc_head, mg_str("rpc.list"), mg_rpc_list, &s_rpc_head);
printf("Starting WS listener on %s/websocket\n", s_listen_on);
mg_http_listen(&mgr, s_listen_on, fn, NULL); // Create HTTP listener
for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop
mg_mgr_free(&mgr); // Deallocate event manager
mg_rpc_del(&s_rpc_head, NULL); // Deallocate RPC handlers
return 0;
}
@@ -0,0 +1 @@
../../../mongoose.c
@@ -0,0 +1 @@
../../../mongoose.h
@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<body>
<h1>JSON-RPC over Websocket demo</h1>
<input id="url" type="text" placeholder="Type URL" value="ws://localhost:8000/websocket" style="width:20em;" />
<button id="connect">connect</button>
<div style="height: 0.3em;">&nbsp;</div>
<button id="btn1">Calculate 1 + 2</button>
<button id="btn2">Calculate 2 * 3</button>
<div style="margin-top: 1em;">Event log:</div>
<div id="log" style="background: #eee; height: 10em; padding: 0.5em; overflow:auto;"><div>
</body>
<script src="rpc-over-websocket.js"></script>
<script>
var rpc, E = function(id) { return document.getElementById(id); };
var url = E('url'), connect = E('connect'), btn1 = E('btn1'), btn2 = E('btn2'), msglog = E('log');
var enable = function(en) { btn1.disabled = btn2.disabled = !en; url.disabled = en; connect.innerHTML = en ? 'disconnect' : 'connect'; };
var log = text => msglog.innerHTML += text + '<br/>\n';
enable(false);
connect.onclick = function() {
console.log(rpc);
if (rpc) { rpc.close(); rpc = null; return; }
rpc = jsonrpc(url.value,
() => enable(true),
() => enable(false),
msg => log('NOTIFICATION: ' + JSON.stringify(msg)));
};
btn1.onclick = ev => rpc.call('sum', [1, 2]).then(res => log('SUM:' + JSON.stringify(res)));
btn2.onclick = ev => rpc.call('mul', [2, 3]).then(res => log('MUL:' + JSON.stringify(res)));
</script>
</html>
@@ -0,0 +1,36 @@
// JSON-RPC over Websocket implementation
var JSONRPC_TIMEOUT_MS = 1000;
var jsonrpc = function(url, onopen, onclose, onnotification) {
var rpcid = 0, pending = {}, ws = new WebSocket(url);
if (!ws) return null;
ws.onclose = onclose;
ws.onmessage = function(ev) {
const frame = JSON.parse(ev.data);
console.log('rcvd', frame, 'pending:', pending);
if (frame.id !== undefined) {
if (pending[frame.id] !== undefined) pending[frame.id](frame); // Resolve
delete (pending[frame.id]);
} else {
if (onnotification) onnotification(frame);
}
};
if (onopen) onopen();
return {
close: () => ws.close(),
call: function(method, params) {
const id = rpcid++, request = {id, method, params};
ws.send(JSON.stringify(request));
console.log('sent', request);
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (pending[id] === undefined) return;
log('Timing out frame ', JSON.stringify(request));
delete (pending[id]);
reject();
}, JSONRPC_TIMEOUT_MS);
pending[id] = x => resolve(x);
});
},
};
};
@@ -0,0 +1,25 @@
PROG ?= example # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
SOURCES = main.c mongoose.c # Source code files
CFLAGS = -W -Wall -Wextra -g -I. # Build options
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
#CFLAGS_MONGOOSE += -DMG_ENABLE_LINES
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= example.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
endif
all: $(PROG) # Default target. Build and run program
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM
@@ -0,0 +1 @@
See detailed tutorial at https://mongoose.ws/tutorials/websocket/websocket-client/
@@ -0,0 +1,43 @@
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// Example Websocket client. Usage:
// 1. Start websocket server: cd ../websocket-server && make
// 2. In another terminal, start this client: make
#include "mongoose.h"
static const char *s_url = "ws://localhost:8000/websocket";
// Print websocket response and signal that we're done
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_OPEN) {
c->is_hexdumping = 1;
} else if (ev == MG_EV_ERROR) {
// On error, log error message
MG_ERROR(("%p %s", c->fd, (char *) ev_data));
} else if (ev == MG_EV_WS_OPEN) {
// When websocket handshake is successful, send message
mg_ws_send(c, "hello", 5, WEBSOCKET_OP_TEXT);
} else if (ev == MG_EV_WS_MSG) {
// When we get echo response, print it
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
printf("GOT ECHO REPLY: [%.*s]\n", (int) wm->data.len, wm->data.buf);
}
if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE || ev == MG_EV_WS_MSG) {
*(bool *) c->fn_data = true; // Signal that we're done
}
}
int main(void) {
struct mg_mgr mgr; // Event manager
bool done = false; // Event handler flips it to true
struct mg_connection *c; // Client connection
mg_mgr_init(&mgr); // Initialise event manager
mg_log_set(MG_LL_DEBUG); // Set log level
c = mg_ws_connect(&mgr, s_url, fn, &done, NULL); // Create client
while (c && done == false) mg_mgr_poll(&mgr, 1000); // Wait for echo
mg_mgr_free(&mgr); // Deallocate resources
return 0;
}
+1
View File
@@ -0,0 +1 @@
../../../mongoose.c
+1
View File
@@ -0,0 +1 @@
../../../mongoose.h
@@ -0,0 +1,25 @@
PROG ?= example # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
SOURCES = main.c mongoose.c # Source code files
CFLAGS = -W -Wall -Wextra -g -I. # Build options
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= example.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
endif
all: $(PROG) # Default target. Build and run program
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM
@@ -0,0 +1 @@
See detailed tutorial at https://mongoose.ws/tutorials/websocket/websocket-server/
@@ -0,0 +1,47 @@
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// Example Websocket server. See https://mongoose.ws/tutorials/websocket-server/
#include "mongoose.h"
static const char *s_listen_on = "ws://localhost:8000";
static const char *s_web_root = ".";
// This RESTful server implements the following endpoints:
// /websocket - upgrade to Websocket, and implement websocket echo server
// /rest - respond with JSON string {"result": 123}
// any other URI serves static files from s_web_root
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_OPEN) {
// c->is_hexdumping = 1;
} else if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/websocket"), NULL)) {
// Upgrade to websocket. From now on, a connection is a full-duplex
// Websocket connection, which will receive MG_EV_WS_MSG events.
mg_ws_upgrade(c, hm, NULL);
} else if (mg_match(hm->uri, mg_str("/rest"), NULL)) {
// Serve REST response
mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123);
} else {
// Serve static files
struct mg_http_serve_opts opts = {.root_dir = s_web_root};
mg_http_serve_dir(c, ev_data, &opts);
}
} else if (ev == MG_EV_WS_MSG) {
// Got websocket frame. Received data is wm->data. Echo it back!
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
mg_ws_send(c, wm->data.buf, wm->data.len, WEBSOCKET_OP_TEXT);
}
}
int main(void) {
struct mg_mgr mgr; // Event manager
mg_mgr_init(&mgr); // Initialise event manager
printf("Starting WS listener on %s/websocket\n", s_listen_on);
mg_http_listen(&mgr, s_listen_on, fn, NULL); // Create HTTP listener
for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop
mg_mgr_free(&mgr);
return 0;
}
+1
View File
@@ -0,0 +1 @@
../../../mongoose.c
+1
View File
@@ -0,0 +1 @@
../../../mongoose.h
@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Websocket test client</h1>
<input id="url" type="text" placeholder="Type URL" value="ws://localhost:8000/websocket" style="width:20em;" />
<button id="connect">connect</button>
<div style="height: 0.3em;">&nbsp;</div>
<input id="message" type="text" placeholder="Type message" style="width: 20em;" />
<button id="send">send message</button>
<div style="margin-top: 1em;">Event log:</div>
<div id="log" style="background: #eee; height: 10em; padding: 0.5em;"><div>
</body>
<script>
var ws, E = function(id) { return document.getElementById(id); };
var url = E('url'), connect = E('connect'), message = E('message'), send = E('send'), log = E('log');
var enable = function(en) { message.disabled = send.disabled = !en; url.disabled = en; connect.innerHTML = en ? 'disconnect' : 'connect'; };
enable(false)
connect.onclick = function() {
if (ws) { ws.close(); return; }
ws = new WebSocket(url.value);
if (!ws) return;
ws.onopen = function() { log.innerHTML += 'CONNECTION OPENED<br/>'; }
ws.onmessage = function(ev) { log.innerHTML += 'RECEIVED: ' + ev.data + '<br/>'; }
ws.onerror = function(ev) { log.innerHTML += 'ERROR: ' + ev + '<br/>'; }
ws.onclose = function() { log.innerHTML += 'CONNECTION CLOSED<br/>'; enable(false); ws = null; }
enable(true);
};
send.onclick = function() {
if (!ws) return;
log.innerHTML += 'SENT: ' + message.value + '<br/>';
ws.send(message.value);
}
</script>
</html>