Changeset

12411:e132a4279914

net.connect: Support for multiple pending connection attempts
author Matthew Wild <mwild1@gmail.com>
date Fri, 18 Mar 2022 16:16:01 +0000 (2022-03-18)
parents 12410:596625eed326
children 12412:18a3a6218100
files net/connect.lua
diffstat 1 files changed, 10 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/net/connect.lua	Fri Mar 18 16:13:09 2022 +0000
+++ b/net/connect.lua	Fri Mar 18 16:16:01 2022 +0000
@@ -28,10 +28,6 @@
 
 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 @@
 			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 @@
 		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 @@
 		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 @@
 		listeners = assert(listeners);
 		options = options or {};
 		data = data;
+		conns = {};
 	}, pending_connection_mt);
 
 	p:log("debug", "Starting connection process");