@@ -39,6 +39,9 @@ class Client
3939 # Number of seconds to wait for acknowledgement packets (default is 5 seconds)
4040 attr_accessor :ack_timeout
4141
42+ # Number of seconds to connect to the server (default is 90 seconds)
43+ attr_accessor :connect_timeout
44+
4245 # Username to authenticate to the server with
4346 attr_accessor :username
4447
@@ -72,6 +75,7 @@ class Client
7275 :clean_session => true ,
7376 :client_id => nil ,
7477 :ack_timeout => 5 ,
78+ :connect_timeout => 30 ,
7579 :username => nil ,
7680 :password => nil ,
7781 :will_topic => nil ,
@@ -239,7 +243,7 @@ def connect(clientid = nil)
239243
240244 unless connected?
241245 # Create network socket
242- tcp_socket = TCPSocket . new ( @host , @port )
246+ tcp_socket = open_tcp_socket
243247
244248 if @ssl
245249 # Set the protocol version
@@ -600,6 +604,19 @@ def next_packet_id
600604 @last_packet_id
601605 end
602606
607+ def open_tcp_socket
608+ return TCPSocket . new @host , @port , connect_timeout : @connect_timeout if RUBY_VERSION . to_f >= 3.0
609+
610+ begin
611+ Timeout . timeout ( @connect_timeout ) do
612+ return TCPSocket . new ( @host , @port )
613+ end
614+ rescue Timeout ::Error
615+ raise IO ::TimeoutError , "Connection timed out for \" #{ @host } \" port #{ @port } " if defined? IO ::TimeoutError
616+ raise Errno ::ETIMEDOUT , "Connection timed out for \" #{ @host } \" port #{ @port } "
617+ end
618+ end
619+
603620 # ---- Deprecated attributes and methods ---- #
604621 public
605622
0 commit comments