-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ irb -r ./select_server | |
>> client.puts "hi" | |
=> nil | |
>> client.puts "bye" | |
=> nil | |
>> client.close | |
=> nil | |
>> exit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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