jart / blink

tiniest x86-64-linux emulator
ISC License
6.95k stars 220 forks source link

enable networking for emscripten #62

Open belaviyo opened 1 year ago

belaviyo commented 1 year ago

In case it helps improving the WASM port, I was able to perform a simple socket connection following these steps:

  1. add these headers to blink.c; reference
    
    #ifdef __EMSCRIPTEN__
    #include <emscripten.h>
    #include <emscripten/websocket.h>
    #include <emscripten/threading.h>
    #include <emscripten/posix_socket.h>

static EMSCRIPTEN_WEBSOCKET_T bridgeSocket = 0;

endif


2. make sure the WebSocket is ready when calling a method:
```cc
int main(int argc, char *argv[]) {
#ifdef __EMSCRIPTEN__
  if (!bridgeSocket) {
    bridgeSocket = emscripten_init_websocket_to_posix_socket_bridge("ws://localhost:8080");
    // Synchronously wait until connection has been established.
    uint16_t readyState = 0;
    do {
      emscripten_websocket_get_ready_state(bridgeSocket, &readyState);
      emscripten_thread_sleep(100);
    } while (readyState == 0);
  }
#endif
....
  1. Link with flags -lwebsocket.js -sPROXY_POSIX_SOCKETS -sUSE_PTHREADS -sPROXY_TO_PTHREAD reference
  2. Have a local server running; https://github.com/emscripten-core/emscripten/tree/main/tools/websocket_to_posix_proxy
    ./websocket_to_posix_proxy 8080
belaviyo commented 1 year ago

https://github.com/jart/blink/discussions/22