Skip to content

Instantly share code, notes, and snippets.

@bboe
Last active Oct 11, 2017
Embed
What would you like to do?
Ruby Simple TCP Echo Servers
#!/usr/bin/env ruby
require './common.rb'
require 'socket'
def main
server = server_socket('0.0.0.0', 1024)
loop do
handle_client(*server.accept)
end
0 # Return code
end
exit main || 0 if __FILE__ == $PROGRAM_NAME
#!/usr/bin/env ruby
require './common.rb'
require 'socket'
def main
server = server_socket('0.0.0.0', 1024)
loop do
# TODO: Clean up terminated child processes
client, addrinfo = server.accept
if fork
client.close # Clean up on server
else
server.close # Clean up on client
handle_client(client, addrinfo)
break
end
end
0 # Return code
end
exit main || 0 if __FILE__ == $PROGRAM_NAME
#!/usr/bin/env ruby
require './common.rb'
require 'socket'
def clean_up_children
loop do
Process.wait # Gather processes as they exit
end
rescue Interrupt
Process.kill('HUP', 0) # Kill all children when main process is terminated
rescue SystemCallError
puts 'All children have exited. Goodbye!'
end
def main
server = server_socket('0.0.0.0', 1024)
4.times do # Adjust this number for the pool size
next unless fork.nil? # Parent only calls fork
loop do # Child does this work
handle_client(*server.accept)
end
return 0
end
clean_up_children
0 # Return code
end
exit main || 0 if __FILE__ == $PROGRAM_NAME
def handle_client(client, addrinfo)
send(client, " Connected: #{addrinfo.inspect}\n")
begin
process_requests(client)
puts "Disconnected: #{addrinfo.inspect}\n"
rescue Errno::ECONNRESET, Errno::EPIPE
puts " Reset: #{addrinfo.inspect}\n"
end
client.close
end
def process_requests(socket)
data = socket.recv(1024)
while data != ''
send(socket, data)
data = socket.recv(1024)
end
end
def send(socket, message)
print message
socket.write(message)
end
def server_socket(addr, port)
socket = Socket.new(:INET, :SOCK_STREAM)
socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
socket.bind(Addrinfo.tcp(addr, port))
socket.listen(1)
puts 'Waiting for connections...'
socket
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment