@@ -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
224225static 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