class TCPServer
inherits TCPSocket
¶
A Transmission Control Protocol (TCP/IP) server.
Usage example:
require "socket"
def handle_client(client)
message = client.gets
client.puts message
end
server = TCPServer.new("localhost", 1234)
while client = server.accept?
spawn handle_client(client)
end
Options:
- backlog to specify how many pending connections are allowed;
- reuse_port to enable multiple processes to bind to the same port (SO_REUSEPORT
).
Included modules
Socket::Server
Class methods¶
.open(port : Int, backlog = SOMAXCONN, reuse_port = false
¶
(port : Int, backlog = SOMAXCONN, reuse_port = false
Creates a new TCP server, listening on all interfaces, and yields it to the block. Eventually closes the server socket when the block returns.
Returns the value of the block.
.open(host, port, backlog = SOMAXCONN, reuse_port = false
¶
(host, port, backlog = SOMAXCONN, reuse_port = false
Creates a new TCP server and yields it to the block. Eventually closes the server socket when the block returns.
Returns the value of the block.
.new(host : String, port : Int, backlog : Int = SOMAXCONN, dns_timeout = nil, reuse_port : Bool = false)
¶
(host : String, port : Int, backlog : Int = SOMAXCONN, dns_timeout = nil, reuse_port : Bool = false)
Binds a socket to the host and port combination.
.new(port : Int, backlog = SOMAXCONN, reuse_port = false)
¶
(port : Int, backlog = SOMAXCONN, reuse_port = false)
Creates a new TCP server, listening on all local interfaces (::
).
.new(*, fd : Int32, family : Family = Family::INET)
¶
(*, fd : Int32, family : Family = Family::INET)
Creates a TCPServer from an already configured raw file descriptor
Methods¶
#accept? : TCPSocket?
¶
: TCPSocket?
Accepts an incoming connection.
Returns the client TCPSocket
or nil
if the server is closed after invoking
this method.
require "socket"
server = TCPServer.new(2022)
loop do
if socket = server.accept?
# handle the client in a fiber
spawn handle_connection(socket)
else
# another fiber closed the server
break
end
end