TCPServer is Ruby’s socket-based class for starting a TCP server. Instantiate it with a port, call accept to wait for a client, and use the returned connection socket to exchange data. section 14.5.2
A small server follows a repeating connection-handling pattern:
- Load the socket library with require 'socket'. section 14.5.2
- Create the listening socket with TCPServer.new(port). section 14.5.2
- Call accept to wait for an incoming TCP connection. section 14.5.2
- Use puts, print, gets, or readline on the connection socket, then close it. section 14.5.2 section 14.5.3
- Keep accepting connections in a loop; create a thread for each connection when one client must not block others. section 14.5.2
A date server
require 'socket' s = TCPServer.new(3939) while (conn = s.accept) conn.puts "Hi. Here's the date." conn.puts Time.now.strftime("%c") conn.close end The listening socket remains available for later clients, while each accepted connection receives the current date and then closes. section 14.5.2
require 'socket'
s = TCPServer.new(3939)
while (conn = s.accept) 1
Thread.new(conn) do |c| 1
c.print "Hi. What's your name? "
name = c.gets.chomp 1
c.puts "Hi, #{name}. Here's the date."
c.puts Time.now.strftime("%c")
c.close
end
end
The threaded variant shows how TCPServer accepts connections continuously while each client interaction runs in its own thread. section 14.5.2
Listing 14.3 Chat server using TCPServer and threads
require 'socket' 1
def welcome(chatter) 2
chatter.print "Welcome! Please enter your name: "
chatter.readline.chomp
end
def broadcast(message, chatters) 3
chatters.each do |chatter|
chatter.puts message
end
end
s = TCPServer.new(3939) 4
chatters = []
while (chatter = s.accept) 5
Thread.new(chatter) do |c|
name = welcome(chatter) 6
broadcast("#{name} has joined", chatters)
chatters << chatter
begin 7
loop do
line = c.readline 8
broadcast("#{name}: #{line}", chatters) 8
end
rescue EOFError 9
c.close
chatters.delete(c) 10
broadcast("#{name} has left", chatters) 10
end
end
end
The chat-server listing extends TCPServer from one response per connection to shared client tracking, broadcasts, and EOFError cleanup. section 14.5.3
