From f278c021e68f508383e8a7b67e5e491614c61def Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Fri, 18 Mar 2022 16:16:01 +0000 Subject: net.connect: Support for multiple pending connection attempts --- net/connect.lua | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'net') diff --git a/net/connect.lua b/net/connect.lua index 4b602be4..6bc5e6b5 100644 --- a/net/connect.lua +++ b/net/connect.lua @@ -28,10 +28,6 @@ local pending_connection_listeners = {}; local function attempt_connection(p) p:log("debug", "Checking for targets..."); - if p.conn then - pending_connections_map[p.conn] = nil; - p.conn = nil; - end p.target_resolver:next(function (conn_type, ip, port, extra) if not conn_type then -- No more targets to try @@ -49,7 +45,7 @@ local function attempt_connection(p) p.last_error = err or "unknown reason"; return attempt_connection(p); end - p.conn = conn; + p.conns[conn] = true; pending_connections_map[conn] = p; end); end @@ -62,6 +58,13 @@ function pending_connection_listeners.onconnect(conn) return; end pending_connections_map[conn] = nil; + if p.connected then + -- We already succeeded in connecting + p.conns[conn] = nil; + conn:close(); + return; + end + p.connected = true; p:log("debug", "Successfully connected"); conn:setlistener(p.listeners, p.data); return p.listeners.onconnect(conn); @@ -73,6 +76,7 @@ function pending_connection_listeners.ondisconnect(conn, reason) log("warn", "Failed connection, but unexpected!"); return; end + p.conns[conn] = nil; p.last_error = reason or "unknown reason"; p:log("debug", "Connection attempt failed: %s", p.last_error); attempt_connection(p); @@ -85,6 +89,7 @@ local function connect(target_resolver, listeners, options, data) listeners = assert(listeners); options = options or {}; data = data; + conns = {}; }, pending_connection_mt); p:log("debug", "Starting connection process"); -- cgit v1.2.3