>>>>> "V" == Ville Mattila <mulperi / iki.fi> writes:

V>         Unfortunately this example does not show how to connect to
V>         server from the same ruby script, by using TCPSocket for example.


pigeon% cat b.rb
#!/usr/bin/ruby
require "socket"

server = Thread.new do
   gs = TCPserver.open('localhost', 8888)
   addr = gs.addr
   addr.shift
   printf("server is on %s\n", addr.join(":"))

   while true
      ns = gs.accept
      print(ns, " is accepted\n")
      Thread.start do
         s = ns                      # save to dynamic variable
         while s.gets
            puts "Received #$_"
         end
         print(s, " is gone\n")
         s.close
      end
   end
end

for i in 1 .. 3
   cs = TCPSocket.new('localhost', 8888);
   cs.print "foobar #{i}"
   cs.close
end

server.join
pigeon% 

pigeon% b.rb
server is on 8888:localhost:127.0.0.1
#<TCPSocket:0x401a52f8> is accepted
#<TCPSocket:0x401a51a4> is accepted
Received foobar 1
#<TCPSocket:0x401a5050> is accepted
#<TCPSocket:0x401a52f8> is gone
Received foobar 2
#<TCPSocket:0x401a51a4> is gone
Received foobar 3
#<TCPSocket:0x401a5050> is gone
^C
./b.rb:30:in `join': Interrupt
        from ./b.rb:30
pigeon% 


Guy Decoux