1998-01-16 15:13:05 +03:00
|
|
|
# socket example - server side
|
|
|
|
# usage: ruby svr.rb
|
|
|
|
|
2005-07-06 13: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 15:13:05 +03:00
|
|
|
require "socket"
|
|
|
|
|
2009-08-03 13:26:26 +04:00
|
|
|
gs = TCPServer.open(0)
|
1998-01-16 15:13:05 +03:00
|
|
|
addr = gs.addr
|
|
|
|
addr.shift
|
2000-11-16 10:24:21 +03:00
|
|
|
printf("server is on %s\n", addr.join(":"))
|
1998-01-16 15:13:05 +03:00
|
|
|
socks = [gs]
|
|
|
|
|
2002-12-19 23:26:16 +03:00
|
|
|
loop do
|
1998-01-16 15:13:05 +03: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 13:47:08 +04:00
|
|
|
# single thread gets may block whole service
|
2011-05-15 15:55:52 +04:00
|
|
|
elsif str = s.gets
|
1998-01-16 15:13:05 +03:00
|
|
|
s.write(str)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|