diff --git a/examples/AutomaticPortSelection.js b/examples/AutomaticPortSelection.js new file mode 100644 index 0000000..584030e --- /dev/null +++ b/examples/AutomaticPortSelection.js @@ -0,0 +1,20 @@ +/* Same as HelloWorld, but with automatic port selection. */ + +const uWS = require('../dist/uws.js'); +let port = 0; + +const app = uWS./*SSL*/App({ + key_file_name: 'misc/key.pem', + cert_file_name: 'misc/cert.pem', + passphrase: '1234' +}).get('/*', (res, req) => { + res.end('Hello World!'); +}).listen(port, (token) => { + if (token) { + // retrieve listening port + port = uWS.us_socket_local_port(token); + console.log('Listening to port ' + port); + } else { + console.log('Failed finding available port'); + } +}); diff --git a/src/addon.cpp b/src/addon.cpp index 53b2bc3..85eec36 100644 --- a/src/addon.cpp +++ b/src/addon.cpp @@ -127,6 +127,12 @@ void uWS_us_listen_socket_close(const FunctionCallbackInfo &args) { us_listen_socket_close(0, (struct us_listen_socket_t *) External::Cast(*args[0])->Value()); } +void uWS_us_socket_local_port(const FunctionCallbackInfo &args) { + // this should take int ssl first, but us_socket_local_port doesn't use it so it doesn't matter + int port = us_socket_local_port(0, (struct us_socket_t *) External::Cast(*args[0])->Value()); + args.GetReturnValue().Set(Integer::New(args.GetIsolate(), port)); +} + /* Temporary KV store (doesn't belong here) */ #include #include @@ -365,6 +371,7 @@ PerContextData *Main(Local exports) { /* Expose some µSockets functions directly under uWS namespace */ exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "us_listen_socket_close", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_us_listen_socket_close)->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()).ToChecked(); + exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "us_socket_local_port", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_us_socket_local_port)->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()).ToChecked(); /* Compression enum */ exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "DISABLED", NewStringType::kNormal).ToLocalChecked(), Integer::NewFromUnsigned(isolate, uWS::DISABLED)).ToChecked();