TCP sockets

suggest change

Ruby provides comprehensive networking support out of the box via the built-in socket library. TCPSocket (for client connections) and TCPServer (for listening services) inherit from IO, which means familiar stream methods such as puts, gets, read, write, and close work directly on socket handles.


1. TCP Client with TCPSocket

To establish a TCP connection to a remote host and port, use TCPSocket.new or TCPSocket.open:

require 'socket'

# Block form ensures the socket is closed automatically
TCPSocket.open('example.com', 80) do |socket|
  # Send an HTTP request
  socket.print "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"

  # Read the response line by line
  while (line = socket.gets)
    puts line
  end
end

Manual Socket Lifecycle and Timeouts

require 'socket'

begin
  # connect_timeout limits how long connecting may take
  socket = TCPSocket.new('127.0.0.1', 8080, connect_timeout: 5)
  socket.timeout = 5 # Ruby 3.2+: limit each blocking read/write

  socket.puts "PING"
  response = socket.gets
  puts "Received: #{response}"
rescue Errno::ECONNREFUSED
  puts "Connection refused. Server is offline."
rescue IO::TimeoutError, Errno::ETIMEDOUT
  puts "Connection timed out."
ensure
  socket.close if socket && !socket.closed?
end

2. Basic TCP Server with TCPServer

A TCPServer binds to a local port and waits for incoming connections using .accept:

require 'socket'

# Bind to localhost on port 4242
server = TCPServer.new('127.0.0.1', 4242)
puts "Echo server listening on 127.0.0.1:4242..."

loop do
  # Blocks until a client connects, returning a connected TCPSocket
  client = server.accept
  
  begin
    puts "Client connected: #{client.peeraddr.inspect}"
    client.puts "Welcome! Send lines to echo, or 'quit' to disconnect."

    while (message = client.gets)
      message = message.chomp
      break if message.downcase == 'quit'

      client.puts "ECHO: #{message}"
    end
  ensure
    client.close
    puts "Client disconnected."
  end
end

3. Concurrent Multi-Threaded TCP Server

A single-threaded server.accept loop can only serve one client at a time. Spawning a new thread per accepted client allows serving multiple concurrent clients:

require 'socket'

server = TCPServer.new(4242)
puts "Multi-threaded server running on port 4242..."

# Ctrl+C raises Interrupt in the main thread (waiting in accept).
# Don't close the server from a trap handler: that fails while accept is blocked.
begin
  loop do
    # Wait for a client connection
    client = server.accept

    # Handle each client in its own thread
    Thread.new(client) do |conn|
      remote_ip = conn.peeraddr[3]
      puts "[+] New connection from #{remote_ip}"

      begin
        conn.puts "Hello #{remote_ip}! Type messages below:"
        while (line = conn.gets)
          break if line.strip == "exit"
          conn.puts "Ack: #{line.strip}"
        end
      rescue Errno::ECONNRESET, Errno::EPIPE
        puts "[-] Connection reset by #{remote_ip}"
      ensure
        conn.close
        puts "[-] Connection closed for #{remote_ip}"
      end
    end
  end
rescue Interrupt
  puts "\nShutting down server..."
  server.close
end

4. Non-Blocking Sockets and Event Multiplexing with IO.select

For high-concurrency servers or event loops without creating thousands of OS threads, use IO.select or non-blocking calls:

require 'socket'

server = TCPServer.new('127.0.0.1', 9000)
clients = []

puts "Non-blocking multiplexer listening on port 9000..."

loop do
  # Check which sockets are ready for reading (timeout: 1.0 second)
  readable, = IO.select([server] + clients, nil, nil, 1.0)
  next unless readable

  readable.each do |sock|
    if sock == server
      # New incoming connection
      new_client = server.accept_nonblock
      clients << new_client
      new_client.puts "Connected to multiplexed server."
    else
      # Client has sent data
      begin
        data = sock.read_nonblock(1024)
        sock.write("Echo: #{data}")
      rescue EOFError, Errno::ECONNRESET
        # Client disconnected
        clients.delete(sock)
        sock.close
      end
    end
  end
end

5. Graceful Socket Shutdown

Closing a socket ends both directions of the connection at once. For half-close (e.g. signaling that sending is complete while still listening for a response), use shutdown:

require 'socket'

socket = TCPSocket.new('127.0.0.1', 8080)

socket.write("PAYLOAD_DATA")
# Flush output and signal EOF to server on write side (SHUT_WR)
socket.shutdown(Socket::SHUT_WR)

# Still read responses from the server
response = socket.read
puts "Server response: #{response}"

socket.close

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents