emscripten-core / emscripten

Emscripten: An LLVM-to-WebAssembly Compiler
Other
25.68k stars 3.29k forks source link

Connect to POSIX TCP Sockets over WebSockets #20921

Closed tbuchs closed 7 months ago

tbuchs commented 9 months ago

I try to compile a C++ framework where the Networking is done over POSIX sockets. I compile the program with the flags -sWEBSOCKET_URL='ws://' -sSOCKET_DEBUG=1 -sWEBSOCKET_SUBPROTOCOL='binary'. The debug message says: 'connect: ws://127.0.0.1:5000/, binary' and 'websocket adding peer: 127.0.0.1:5000'.

I do this in a loop (on a worker), however after a while I get 'Socket error ,14,ECONNREFUSED: Connection refused' 'Socket error 4,23,EHOSTUNREACH: Host is unreachable'

I also run the websockify with './websockify :5000 127.0.0.1:4999 --cert=...'

      mysocket = socket(PF_INET, SOCK_STREAM, 0);
       if (mysocket < 0)
         error

       // set non-blocking
       int flags = fcntl(mysocket, F_GETFL, 0);
       fl = fcntl(mysocket, F_SETFL, O_NONBLOCK | flags);
       if (fl<0)
          error

       fl = connect(mysocket, addr, len);
       if (fl != 0 && errno == EINPROGRESS)
       {
            fd_set fdr;
            fd_set fdw;

            FD_ZERO(&fdr);
            FD_ZERO(&fdw);
            FD_SET(mysocket, &fdr);
            FD_SET(mysocket, &fdw);

            int res = select(int(mysocket + 1), &fdr, &fdw, NULL, NULL);
tbuchs commented 9 months ago

I found the idea to replace the select call with a sleep to wait until the connection is ready - seems a bit hacky, but works. Is there any better way to achive this? (see here: https://github.com/emscripten-core/emscripten/issues/18383#issuecomment-1357287776)