1998-01-16 07:13:05 -05:00
|
|
|
# socket example - server side
|
|
|
|
# usage: ruby svr.rb
|
|
|
|
|
2005-07-06 05:47:08 -04:00
|
|
|
# this server might be blocked by an ill-behaved client.
|
|
|
|
# see tsvr.rb which is safe from client blocking.
|
|
|
|
|
1998-01-16 07:13:05 -05:00
|
|
|
require "socket"
|
|
|
|
|
2009-08-03 05:26:26 -04:00
|
|
|
gs = TCPServer.open(0)
|
1998-01-16 07:13:05 -05:00
|
|
|
addr = gs.addr
|
|
|
|
addr.shift
|
2000-11-16 02:24:21 -05:00
|
|
|
printf("server is on %s\n", addr.join(":"))
|
1998-01-16 07:13:05 -05:00
|
|
|
socks = [gs]
|
|
|
|
|
2002-12-19 15:26:16 -05:00
|
|
|
loop do
|
1998-01-16 07:13:05 -05:00
|
|
|
nsock = select(socks);
|
|
|
|
next if nsock == nil
|
|
|
|
for s in nsock[0]
|
|
|
|
if s == gs
|
|
|
|
ns = s.accept
|
|
|
|
socks.push(ns)
|
|
|
|
print(s, " is accepted\n")
|
|
|
|
else
|
|
|
|
if s.eof?
|
|
|
|
print(s, " is gone\n")
|
|
|
|
s.close
|
|
|
|
socks.delete(s)
|
2005-07-06 05:47:08 -04:00
|
|
|
# single thread gets may block whole service
|
|
|
|
elsif str = s.gets
|
1998-01-16 07:13:05 -05:00
|
|
|
s.write(str)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|