File tree Expand file tree Collapse file tree 3 files changed +31
-1
lines changed
Expand file tree Collapse file tree 3 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -82,6 +82,15 @@ client.ca_file = path_to('root-ca.pem')
8282client.connect
8383~~~
8484
85+ The default timeout when opening a TCP Socket is 30 seconds. To specify it explicitly, use 'connect_timeout =>':
86+
87+ ~~~ ruby
88+ client = MQTT ::Client .connect(
89+ :host => ' myserver.example.com' ,
90+ :connect_timeout => 15
91+ )
92+ ~~~
93+
8594The connection can either be made without the use of a block:
8695
8796~~~ ruby
Original file line number Diff line number Diff line change @@ -41,6 +41,9 @@ class Client
4141 # Number of seconds to wait for acknowledgement packets (default is 5 seconds)
4242 attr_accessor :ack_timeout
4343
44+ # Number of seconds to connect to the server (default is 90 seconds)
45+ attr_accessor :connect_timeout
46+
4447 # How many times to attempt re-sending packets that weren't acknowledged
4548 # (default is 5) before giving up
4649 attr_accessor :resend_limit
@@ -84,6 +87,7 @@ class Client
8487 clean_session : true ,
8588 client_id : nil ,
8689 ack_timeout : 5 ,
90+ connect_timeout : 30 ,
8791 resend_limit : 5 ,
8892 reconnect_limit : 5 ,
8993 reconnect_backoff : 2 ,
@@ -496,7 +500,7 @@ def clear_queue
496500
497501 def connect_internal
498502 # Create network socket
499- tcp_socket = TCPSocket . new ( @host , @port )
503+ tcp_socket = open_tcp_socket
500504
501505 if @ssl
502506 # Set the protocol version
@@ -793,5 +797,17 @@ def next_packet_id
793797 @last_packet_id = 1 if @last_packet_id > 0xffff
794798 @last_packet_id
795799 end
800+
801+ def open_tcp_socket
802+ return TCPSocket . new @host , @port , connect_timeout : @connect_timeout if RUBY_VERSION . to_f >= 3.0
803+
804+ begin
805+ Timeout . timeout ( @connect_timeout ) do
806+ return TCPSocket . new ( @host , @port )
807+ end
808+ rescue Timeout ::Error
809+ raise IO ::TimeoutError , "Connection timed out for \" #{ @host } \" port #{ @port } "
810+ end
811+ end
796812 end
797813end
Original file line number Diff line number Diff line change @@ -626,6 +626,11 @@ def register_for_ack(packet)
626626 end
627627 end
628628
629+ it "respects connect_timeout" do
630+ client = MQTT ::Client . new ( host : "198.51.100.1" , connect_timeout : 0.1 )
631+ expect { client . connect } . to raise_error ( IO ::TimeoutError )
632+ end
633+
629634 it "respects timeouts" do
630635 require "socket"
631636 rd , _wr = UNIXSocket . pair
You can’t perform that action at this time.
0 commit comments