How to write TCPServer code that can exit?

Hi all

I've got a bit of a problem with my network code. Perhaps someone can
help me out with this:

I've got a program in which I run a TCP server. The code is basically
like this:

def start_server
  s = TCPServer.new(@port)
  loop do
    Thread.start(s.accept) do |session|
      # handle incoming connections...
    end
  end
end

The server code works just fine. However, my problem is that as it is,
Im having trouble testing it. Once the server is initiated, I can't shut
it down in code. Thus Im not able to figure out how to do rspec examples
with it. If I try to start the server code in an rspec example and run
some client stuff to test it, I never get to the next examples, because
the server code wont quit. It just runs forever.

Is there a better way to do this, so I can shut it down at will, and be
able to make a proper test suite?

Best regards,
Chris

···

--
Posted via http://www.ruby-forum.com/.

I think you need to generally think about how that server will be shut
down. There are a few options I can think of off the top of my head:

- if the protocol allows it reserve a message for shutdown so clients
can terminate the server
- write a signal handler which cleanly shuts down the server (for
example close listening socket, wait for all client threads to
terminate); to support that your server could write out its pid to a
well known location (e.g. /var/run).

Kind regards

robert

···

On Fri, Oct 28, 2011 at 10:11 AM, Chris Lervag <chris.lervag@gmail.com> wrote:

I've got a bit of a problem with my network code. Perhaps someone can
help me out with this:

I've got a program in which I run a TCP server. The code is basically
like this:

def start_server
s = TCPServer.new(@port)
loop do
Thread.start(s.accept) do |session|
# handle incoming connections...
end
end
end

The server code works just fine. However, my problem is that as it is,
Im having trouble testing it. Once the server is initiated, I can't shut
it down in code. Thus Im not able to figure out how to do rspec examples
with it. If I try to start the server code in an rspec example and run
some client stuff to test it, I never get to the next examples, because
the server code wont quit. It just runs forever.

Is there a better way to do this, so I can shut it down at will, and be
able to make a proper test suite?

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/