Search code examples
rubytcptcpclient

Code for sending a message or file over TCP in Ruby


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.

I'm looking for example 'client' and 'server' scripts that will work straight away, once I've chosen ports that work.

Client code I found that seems to work, shown below.

But I haven't got a server working with it.

# 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

I'm interested in the simplest possible solution, that works on my machine.

All it has to do is send a string. The answer I'm looking for is just like this but with ruby, instead of python.

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.

Server 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

Using the code suggested by kennycoc I get the following error message

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 `<main>'

Solution

  • @adjam you haven't created a TcpServer, TCPSocket is used to create TCP/IP client socket

    To create TCP/IP server you have to use TCPServer

    EX: Tcp/ip Server code:

    require 'socket'
    server = TCPServer.open(2000)
    client = server.accept # Accept client
    while (response = client.gets) # read data send by client
     print response
    end
    

    Tcp/ip Client code:

    require 'socket'
    client = TCPSocket.open('localhost', 2000)
    client.puts "hello"
    client.close;