cpp-httplib icon indicating copy to clipboard operation
cpp-httplib copied to clipboard

Emscripten POSIX socket support

Open theo-dep opened this issue 3 months ago • 2 comments

I am prototyping an Emscripten httplib::Client build using the Emulated POSIX TCP Sockets over WebSockets tutorial. For the work, see this commit: 49b526c1ec4a8c09bba0f5163c004024b5130a8c.

Are you interested in this kind of development?

I’m not entirely convinced it’s a good idea myself, but the Emscripten Fetch API is much more difficult to use and less documented compared to cpp-httplib.

With my prototype, I can build and run the following small example in a browser:

// main.cpp
#include <httplib.h>
#include <print>

int main()
{
#ifdef __EMSCRIPTEN__
    httplib::emscripten_init_websocket("ws://localhost:8080");
#endif

    httplib::Client cli("http://yhirose.github.io");

    auto res = cli.Get("/hi");
    std::println("Status: {}", res->status);
    std::println("Body: {}", res->body);

    return 0;
}

The build command and execution with emrun are as follows:

em++ -std=c++23 -o index.html main.cpp -lwebsocket.js -sPROXY_POSIX_SOCKETS -pthread -sPROXY_TO_PTHREAD -sMEMORY64 -sEXIT_RUNTIME

This approach requires the Emscripten bridge socket server, websocket_to_posix_proxy, or a Node.js WebSocket server implementation. I haven’t yet figured out how to deploy this in a production environment, hence my questions about the prototype.

I started a functional project demonstrator.

theo-dep avatar Oct 31 '25 13:10 theo-dep

@theo-dep, thanks for sharing this interesting attempt! I don't currently have any projects that require Emscripten's POSIX socket support, but your change is fairly simple, so I don't see any problem including it in httplib.h. When you consider your work complete and production-ready, please submit a pull request with accompanying unit tests.

yhirose avatar Nov 14 '25 22:11 yhirose

I am working on it, but I think the work will be production-ready when:

  • [ ] The client bridge socket is in ClientImpl.
  • [ ] The server WebSocket proxy socket is merged with the current server socket. Could the proxy be a function plugged by callback?
  • [ ] Unit tests include an Emscripten compilation.
  • [ ] The Readme is updated.

The hot points are probably the server double socket, I guess 🤔...

theo-dep avatar Nov 19 '25 18:11 theo-dep