Skip to content

Instantly share code, notes, and snippets.

@keymon
Forked from kyanny/echo.rb
Last active May 17, 2016 16:28
Show Gist options
  • Save keymon/907ef1f942ee532a894c3fabe0aa03de to your computer and use it in GitHub Desktop.
Save keymon/907ef1f942ee532a894c3fabe0aa03de 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'
if ARGV[0]
port = ARGV[0].to_i
else
port = 0
end
gs = TCPServer.open(port)
addr = gs.addr
addr.shift
puts "server is on #{addr.join(':')}"
while true
Thread.start(gs.accept) do |s|
while s.gets
s.write("Received #{$_.length} bytes\n")
s.flush
end
s.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment