Skip to content

Commit 9b3efbd

Browse files
Expose us_socket_local_port (#547)
Usage: ```ts const token: us_socket_t; const port = uWS.us_socket_local_port(token); ```
1 parent 6d88f85 commit 9b3efbd

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

‎examples/AutomaticPortSelection.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/* Same as HelloWorld, but with automatic port selection. */
2+
3+
const uWS = require('../dist/uws.js');
4+
let port = 0;
5+
6+
const app = uWS./*SSL*/App({
7+
key_file_name: 'misc/key.pem',
8+
cert_file_name: 'misc/cert.pem',
9+
passphrase: '1234'
10+
}).get('/*', (res, req) => {
11+
res.end('Hello World!');
12+
}).listen(port, (token) => {
13+
if (token) {
14+
// retrieve listening port
15+
port = uWS.us_socket_local_port(token);
16+
console.log('Listening to port ' + port);
17+
} else {
18+
console.log('Failed finding available port');
19+
}
20+
});

‎src/addon.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,12 @@ void uWS_us_listen_socket_close(const FunctionCallbackInfo<Value> &args) {
127127
us_listen_socket_close(0, (struct us_listen_socket_t *) External::Cast(*args[0])->Value());
128128
}
129129

130+
void uWS_us_socket_local_port(const FunctionCallbackInfo<Value> &args) {
131+
// this should take int ssl first, but us_socket_local_port doesn't use it so it doesn't matter
132+
int port = us_socket_local_port(0, (struct us_socket_t *) External::Cast(*args[0])->Value());
133+
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), port));
134+
}
135+
130136
/* Temporary KV store (doesn't belong here) */
131137
#include <unordered_map>
132138
#include <string>
@@ -365,6 +371,7 @@ PerContextData *Main(Local<Object> exports) {
365371

366372
/* Expose some µSockets functions directly under uWS namespace */
367373
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();
374+
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();
368375

369376
/* Compression enum */
370377
exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "DISABLED", NewStringType::kNormal).ToLocalChecked(), Integer::NewFromUnsigned(isolate, uWS::DISABLED)).ToChecked();

0 commit comments

Comments
 (0)