title: Sockets in Ruby, how can I asynchronously read and write data through a Socket
body: <p>I am trying to build a ruby based background job which is required to establish a TCP socket connection and keep reading from its stream.
  I require the same socket to be open to write data.</p>
  <p>I know the server behind the socket is working as expect as I have other services that can use it.</p>
  <p>I tried to span a background thread, to keep reading the stream, but it never gets data</p>
  <pre><code>@socket = TCPSocket.new(localhost, 1234)
  
  
  def read_data_loop
    while true
      @socket.each_line do |line|
        p &quot;data: #{line}&quot;
      end
    end
  end
  
  @buffer_thread = Thread.new { read_data_loop }
  
  @socket.write(&quot;send me something!!&quot;)
  
  sleep(10)
  @buffer_thread.exit
  </code></pre>
  <p>I am craving for a working example to achieve this async read/write...</p>
  <p>ps. I used <code>TCPSocket</code> in this example because it seamed like a good idea to start with, but I am not sold on it. I will take anything that works</p>