TCPServer
Inherits Socket::Server / TCPSocket / IPSocket / Socket / Crystal::System::Socket / IO::Buffered / IO / Reference / Object
A Transmission Control Protocol (TCP/IP) server.
NOTE: To use TCPServer, you must explicitly import it with require "socket"
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:
- host local interface to bind on, or
::to bind on all local interfaces. - port specific port to bind on, or
0to receive an "ephemeral" (free, assigned by kernel) port. - backlog to specify how many pending connections are allowed.
- reuse_port to enable multiple processes to bind to the same port (
SO_REUSEPORT).
Constructors
Binds a socket to the host and port combination.
Creates a new TCP server, listening on all local interfaces (::).
Creates a TCPServer from an existing system file descriptor or socket handle.
This adopts fd into the IO system that will reconfigure it as per the event loop runtime requirements.
NOTE: On Windows, the handle must have been created with
WSA_FLAG_OVERLAPPED.
Class methods
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.
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.
Instance methods
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