Skip to content

Instantly share code, notes, and snippets.

@maierru
Forked from sandro/client_example
Created November 8, 2019 23:42
Show Gist options
  • Save maierru/6a73aa100c55cd2c2854caa308890f8b to your computer and use it in GitHub Desktop.
Save maierru/6a73aa100c55cd2c2854caa308890f8b to your computer and use it in GitHub Desktop.
Ruby select socket server. An example of a single-threaded, event-driven (select) server.
$ irb -r ./select_server
>> client.puts "hi"
=> nil
>> client.puts "bye"
=> nil
>> client.close
=> nil
>> exit
require 'socket'
if defined?(IRB)
def self.client
@client ||= TCPSocket.open("0.0.0.0", 4242)
end
client
else
begin
acceptor = TCPServer.open("0.0.0.0", 4242)
fds = [acceptor]
while true
puts 'loop'
if ios = select(fds, [], [], 10)
reads = ios.first
p reads
reads.each do |client|
if client == acceptor
puts 'Someone connected to server. Adding socket to fds.'
client, sockaddr = acceptor.accept
fds << client
elsif client.eof?
puts "Client disconnected"
fds.delete(client)
client.close
else
# Perform a blocking-read until new-line is encountered.
# We know the client is writing, so as long as it adheres to the
# new-line protocol, we shouldn't block for very long.
puts "Reading..."
p client.gets("\n")
end
end
end
end
ensure
puts "Cleaning up"
fds.each {|c| c.close}
end
end
$ ruby select_server.rb
loop
[#<TCPServer:fd 3>]
Someone connected to server. Adding socket to fds.
loop
[#<TCPSocket:fd 4>]
Reading...
"hi\n"
loop
[#<TCPSocket:fd 4>]
Reading...
"bye\n"
loop
[#<TCPSocket:fd 4>]
Client disconnected
loop
loop
^Cuni.rb:12:in `select': Interrupt
from uni.rb:12:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment