Skip to content

Instantly share code, notes, and snippets.

@kyanny
Created February 24, 2010 17:43
Show Gist options
  • Save kyanny/313649 to your computer and use it in GitHub Desktop.
Save kyanny/313649 to your computer and use it in GitHub Desktop.
Ruby socket TCPServer echo server
require 'socket'
gs = TCPServer.open(0)
socks = [gs]
addr = gs.addr
addr.shift
puts "server is on #{addr.join(':')}"
while true
nsock = select(socks)
next if nsock == nil
for s in nsock[0]
if s == gs
socks.push(s.accept)
puts "#{s} is accepted"
else
if s.eof?
puts "#{s} is gone"
s.close
socks.delete(s)
else
str = s.gets
s.write(str)
end
end
end
end
require 'socket'
gs = TCPServer.open(0)
addr = gs.addr
addr.shift
puts "server is on #{addr.join(':')}"
while true
Thread.start(gs.accept) do |s|
puts "#{s} is accepted"
while s.gets
s.write($_)
end
puts "#{s} is gone"
s.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment