# Mocking a tcp server

**URL:** <https://www.ruby-forum.com/t/mocking-a-tcp-server/94156>\
**Category:** Ruby\
**Created:** [April 23, 2006, 10:07am UTC](https://www.ruby-forum.com/t/mocking-a-tcp-server/94156 "2006-04-23T10:07:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [April 23, 2006, 10:07am UTC](https://www.ruby-forum.com/t/mocking-a-tcp-server/94156/1 "2006-04-23T10:07:16Z")

</div>

I have an class that should connect to a server and just wait for  
responses. Here’s the class, it’s very basic

```
class Connection
  def initialize(host, port)
    @host, @port = host, port
    @server = TCPSocket.new @host, @port
    listen
  end

  private

  def listen
    Thread.new do
      while cmd = @server.gets
        puts cmd
      end
    end
  end
end

```

This seems to work if I connect to a live server. It’s not working  
perfectly, because it only gets a couple of responses and then quits  
before it has all of them. However, if do t = Thread.new… and then  
call t.join after the thread block, it just hangs there. So I’m not  
sure what to do about that.

Secondly, I don’t know how to mock up the server. I have this class:

class TCPSocket  
def gets  
while $server\_messages.empty?  
# just sit and do nothing  
end

```
  $server_messages.shift
end

```

end

and in my unit tests I add a string to $server\_messages. If I join my  
thread in Connection#listen it just hangs, and if I don’t join, it  
just exits without getting any messages. How can I listen for  
arbitrary messages in another thread, and how can I mock up the  
server?

Pat

---

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [April 23, 2006, 6:41pm UTC](https://www.ruby-forum.com/t/mocking-a-tcp-server/94156/2 "2006-04-23T18:41:46Z")

</div>

On Apr 23, 2006, at 3:04 AM, Pat M. wrote:

> Secondly, I don’t know how to mock up the server.

My recent blog post might give you some ideas:

[http://blog.grayproductions.net/articles/2006/04/21/phoned-in-testing-](http://blog.grayproductions.net/articles/2006/04/21/phoned-in-testing-)  
post

James Edward G. II
