title: Code for sending a message or file over TCP in Ruby
body: <p>I've been trying for a couple of days with limited success to use TCP to make two ruby programs on the same or different machines communicate.</p>
  
  <p>I'm looking for example 'client' and 'server' scripts that will work straight away, once I've chosen ports that work.</p>
  
  <p>Client code I found that seems to work, shown below.</p>
  
  <p>But I haven't got a server working with it.</p>
  
  <pre><code># Seems to work for some reason
  require 'socket'
  
  tcp_client=TCPSocket.new('localhost',1540)
  while grab_string=tcp_client.gets
  puts(grab_string)
  end
  tcp_client.close
  </code></pre>
  
  <p>I'm interested in the simplest possible solution, that works on my machine.</p>
  
  <p>All it has to do is send a string. The answer I'm looking for is just like <a href="https://stackoverflow.com/questions/27241804/sending-a-file-over-tcp-sockets-in-python">this</a> but with ruby, instead of python.</p>
  
  <p>Feel free to change the code for client and server, with only half the puzzle in place I'm not sure if its works or not.</p>
  
  <p>Server code</p>
  
  <pre><code># Server
  require 'socket'
  
  sock = TCPSocket.new('localhost', 1540)
  sock.write 'GETHELLO'
  puts sock.read(5) # Since the response message has 5 bytes.
  sock.close
  </code></pre>
  
  <p>Using the code suggested by kennycoc I get the following error message</p>
  
  <pre><code>Server.rb:3:in `initialize': Only one usage of each socket address (protocol/network address/port) is normally permitted. - bind(2) for nil port 1540 (Errno::EADDRINUSE)
          from Server.rb:3:in `new'
          from Server.rb:3:in `&lt;main&gt;'
  </code></pre>