After poking around the documentation a bit, I managed to do a little
test server program. However, I've run into a little problem:
I wanted to keep all the connections within the same thread and simply
use select() and loops to service all the various connections; however,
the sample server's socket.gets will block the thread until after it
finds a newline. So, I tried using socket.recv(), and it complains
about "recv for buffered IO (IOError)" Socket.gets() did finally work,
but it does seem rather inefficient to read/echo one single character
at a time...
Anyone know what I'm doing wrong?
The stuff below is the test program.
Thanks in advance,
Peter Yu
require "socket"
class DUCKSOCK
@@connections = []
@@handle = nil
def initialize(port)
@@handle = TCPServer.open(port)
@@connections = [@@handle]
end
def poll(pause)
sock = select(@@connections, nil, nil, pause)
return if sock == nil
for s in sock[0]
if (s == @@handle)
conn = s.accept
@@connections.push(conn)
printf ("Connection from %s(%s) on port %s\n", conn.addr[2],
conn.addr[3],
conn.addr[1])
else
if s.eof?
printf("Connection from %s(%s) on port %s lost\n", s.addr[2],
s.addr[3],
s.addr[1])
s.close
@@connections.delete(s)
else
#str = s.gets #This'll block until a newline...
str=s.recvfrom(100)[0]#Complains about "recv for buffered IO"
#char = s.getc #Works, but exceedingly slow.
s.write(str)
end
end
end
end
end
ds = DUCKSOCK.new(2000)
diff = 0
while true
time1 = Time.new
ds.poll(2.0+diff)
time2 = Time.new
elapsed = (time2.to_f-time1.to_f)
diff = 2.0 - elapsed
while (diff < -2.0)
diff += 2.0
printf("Extra!\n");
end
print "Elaspsed %10.20f\n" % elapsed
print time2, "\n"
end
Sent via Deja.com
http://www.deja.com/