Karl-Heinz Wild <kh.wild / wicom.li> wrote:
> I'm playing with the class TcpServer from the
> package ldap-server.
>
> There is an interesting way for me of running a tcp server.
>
> -----------------------------
>
> t = GAME::Server.tcpserver(:port=>1110, :nodelay=>true) do
>     print "+OK I am a fake POP3 server\r\n"
>     while line = gets
>       case line
>       when /^quit/i
>         break
>       else
>         print "-ERR I don't understand #{line}"
>       end
>     end
>     print "+OK bye\r\n"
>   end
>   t.join
> end
>
> ----------------------------
>
> inside the GAME:Server.tcpserver it looks like
>
> ----------------------------
>
>   def self.tcpserver(opt, &blk)
>     server = TCPServer.new(opt[:bindaddr] || "0.0.0.0", opt[:port])
>     server.listen(opt[:listen]) if opt[:listen]
>
>     Thread.new do
>       while true
>         begin
>           session = server.accept
>           Thread.new(session) do |s|
>              s.instance_eval(&blk)
>           end
>         rescue Interrupt
>           server.close if server and not server.closed?
>           break
>         end
>       end
>     end
>   end
>
> ------------------------------
>
> Now, how can I get access to the "session" variables.
> I need some information from TCP inside the block.
> But I couldn't find out how.
>
> Thanks for reading the mail and maybe an answer :)
>
> regards
> Karl-Heinz

I'd prefer to hand over the session to the block as first parameter.  That 
way you don't hide the self of the block's calling context (it might be 
necessary to access that) and you don't loose anything:

   def self.tcpserver(opt, &blk)
     server = TCPServer.new(opt[:bindaddr] || "0.0.0.0", opt[:port])
     server.listen(opt[:listen]) if opt[:listen]

     Thread.new do
       while true
         begin
           Thread.new(server.accept, &blk)
         rescue Interrupt
           server.close if server and not server.closed?
           break
         end
       end
     end
   end

t = GAME::Server.tcpserver(:port=>1110, :nodelay=>true) do |session|
     session.print "+OK I am a fake POP3 server\r\n"
     while line = session.gets
       case line
       when /^quit/i
         break
       else
         session.print "-ERR I don't understand #{line}"
       end
     end
     session.print "+OK bye\r\n"
   end
   t.join
end

Btw, are you sure you want that t.join there?  Looks like it was joining 
with its creator thread - doesn't sound like a good idea because typically 
the creator joins on all its children.

Kind regards

    robert