Module: Lich::Common::ReusableTCPServer
- Defined in:
- documented/common/reusable_tcp_server.rb
Overview
Factory for creating TCP server sockets with SO_REUSEADDR set before binding.
Ruby's TCPServer.new calls bind and listen internally during construction,
so any setsockopt call made after construction is too late - the port is already
bound without the reuse flag. This causes "Address already in use" failures when
restarting quickly because the kernel holds the port in TIME_WAIT for ~60 seconds.
This module separates socket creation from binding so that SO_REUSEADDR takes effect before the port is claimed.
Class Method Summary collapse
-
.create(host, port, backlog: 1) ⇒ Socket
Creates a TCP server socket with SO_REUSEADDR enabled before binding.
Class Method Details
.create(host, port, backlog: 1) ⇒ Socket
Creates a TCP server socket with SO_REUSEADDR enabled before binding.
32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'documented/common/reusable_tcp_server.rb', line 32 def self.create(host, port, backlog: 1) address = Addrinfo.tcp(host, port) server = Socket.new(address.afamily, :STREAM) begin server.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1) server.bind(address) server.listen(backlog) server rescue server.close rescue nil raise end end |