#include "testlib.h"
DValue websocket_suite_event(Request& context, String type, String nonce)
{
DValue event;
event["type"] = type;
event["nonce"] = nonce;
event["connection_id"] = ws_connection_id();
event["scope"] = first(context.params["DOCUMENT_URI"], ws_scope());
event["online"] = (f64)ws_connection_count();
event["opcode"] = (f64)ws_opcode();
event["binary"] = ws_is_binary() ? "true" : "false";
return(event);
}
RENDER(Request& context)
{
String ws_url = context.params["DOCUMENT_URI"];
site_tests_page_start("WebSockets", "Browser-driven handshake and broadcast checks for ws_* helpers on the current .ws.uce endpoint.");
?>
This page self-tests in the browser: it opens a socket to itself, waits for a targeted hello acknowledgment, then verifies a broadcast acknowledgment from the same endpoint.
site_tests_page_end();
}
WS(Request& context)
{
if(ws_is_binary())
{
ws_send_to(ws_connection_id(), json_encode(websocket_suite_event(context, "binary-not-supported", "")));
return;
}
DValue payload = json_decode(ws_message());
String type = trim(payload["type"].to_string());
String nonce = trim(payload["nonce"].to_string());
if(type == "hello")
{
ws_send_to(ws_connection_id(), json_encode(websocket_suite_event(context, "hello-ack", nonce)));
return;
}
if(type == "broadcast")
{
ws_send(json_encode(websocket_suite_event(context, "broadcast-ack", nonce)));
return;
}
ws_send_to(ws_connection_id(), json_encode(websocket_suite_event(context, "unknown", nonce)));
}