Sockets
TCPServer
A TCP server socket listens on a port and waits for clients to connect.
The classic overview also shows
sockets
with a minimal example, and this lesson builds the full flow step by step.
require "socket"
server = TCPServer.new(25110)
puts server.addr.inspect
Accept a client
Accept blocks until a client connects, then returns a client socket for talking to that peer.
Write one line with puts on the client socket and close it when the conversation ends.
require "socket"
server = TCPServer.new(25110)
client = server.accept
client.puts("Hello from Ruby")
client.close
Bind IPv4 explicitly
On many systems a bare port listens on IPv6 only, which confuses
IPv4 clients.
Pass 0.0.0.0 as the host to listen on every IPv4 interface explicitly.
require "socket"
server = TCPServer.new("0.0.0.0", 25110)
puts server.addr.inspect
Close cleanly
Sockets hold operating system resources, so close both the client and the server when done.
An ensure block guarantees cleanup even when accept or the conversation raises.
require "socket"
server = TCPServer.new("0.0.0.0", 25110)
begin
client = server.accept
client.puts("Bye")
ensure
client.close if client
server.close
end
Next: REST APIs
Article author: Arthur Isaev