Running a loop (such as one for a mock webserver) within a thread

Posted by bob c on Stack Overflow See other posts from Stack Overflow or by bob c
Published on 2010-03-02T02:36:40Z Indexed on 2010/04/18 14:03 UTC
Read the original article Hit count: 134

Filed under:
|
|

I'm trying to run a mock webserver within a thread within a class. I've tried passing the class' @server property to the thread block but as soon as I try to do server.accept the thread stops. Is there some way to make this work? I want to basically be able to run a webserver off of this script while still taking user input via stdin.gets. Is this possible?

class Server
    def initialize()
        @server = TCPServer.new(8080)
    end
    def run()
        @thread = Thread.new(@server) { |server|
            while true
                newsock = server.accept
                puts "some stuff after accept!"
                next if !newsock
                # some other stuff
            end
        }
    end
end
def processCommand()
    # some user commands here
end
test = Server.new
while true do
  processCommand(STDIN.gets)
end

In the above sample, the thread dies on server.accept

© Stack Overflow or respective owner

Related posts about ruby

Related posts about oop