Skip to content

Commit 1e82c96

Browse files
authored
Explicit port reuse in net.serve (#276)
Closes #127
1 parent 3626d66 commit 1e82c96

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

examples/parallel_serve_helper.luau

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ local net = require("@lute/net")
22

33
return {
44
serve = function()
5-
net.serve(function(req)
6-
return "Hello, lute!"
7-
end)
5+
net.serve({
6+
handler = function(req)
7+
return "Hello, lute!"
8+
end,
9+
reuseport = true,
10+
})
811
end,
912
}

net/src/net.cpp

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ struct ServerLoopState
219219
std::shared_ptr<Ref> handlerRef;
220220
std::string hostname;
221221
int port;
222+
bool reusePort = false;
222223
};
223224

224225
static void parseQuery(const std::string_view& query, lua_State* L)
@@ -462,9 +463,12 @@ void setupAppAndListen(auto* app, std::shared_ptr<ServerLoopState> state, bool&
462463
}
463464
);
464465

466+
int options = state->reusePort ? LIBUS_LISTEN_DEFAULT : LIBUS_LISTEN_EXCLUSIVE_PORT;
467+
465468
app->listen(
466469
state->hostname,
467470
state->port,
471+
options,
468472
[&success](auto* listen_socket)
469473
{
470474
success = (listen_socket != nullptr);
@@ -506,6 +510,7 @@ int lua_serve(lua_State* L)
506510
{
507511
std::string hostname = "0.0.0.0";
508512
int port = 3000;
513+
bool reusePort = false;
509514
std::optional<uWS::SocketContextOptions> tlsOptions;
510515
int handlerIndex = 1;
511516

@@ -526,6 +531,13 @@ int lua_serve(lua_State* L)
526531
}
527532
lua_pop(L, 1);
528533

534+
lua_getfield(L, 1, "reuseport");
535+
if (lua_isboolean(L, -1))
536+
{
537+
reusePort = lua_toboolean(L, -1);
538+
}
539+
lua_pop(L, 1);
540+
529541
lua_getfield(L, 1, "tls");
530542
if (lua_istable(L, -1))
531543
{
@@ -589,6 +601,7 @@ int lua_serve(lua_State* L)
589601
state->runtime = runtime;
590602
state->hostname = hostname;
591603
state->port = port;
604+
state->reusePort = reusePort;
592605

593606
lua_pushvalue(L, handlerIndex);
594607
state->handlerRef = std::make_shared<Ref>(L, -1);
@@ -614,8 +627,8 @@ int lua_serve(lua_State* L)
614627

615628
if (!success)
616629
{
617-
lua_pushnil(L);
618-
return 1;
630+
luaL_errorL(L, "failed to listen on port %d, is it already in use? consider the reuseport option", port);
631+
return 0;
619632
}
620633

621634
state->loopFunction = [state]()

0 commit comments

Comments
 (0)