Issue
I'm on Fedora 20 and use ruby 2.1.0. I've the following code from rel="nofollow">ruby-doc.
require 'socket'
s = TCPSocket.new 'localhost', 2000
while line = s.gets # Read lines from socket
puts line # and print them
end
s.close # close socket when done
Ruby throws the following error:
client.rb:3:in `initialize': Connection refused - connect(2) for "localhost" port 2000 (Errno::ECONNREFUSED)
from client.rb:3:in `new'
from client.rb:3:in `<main>'
What could be the reason for this failure? I mean, the code should definitively work, it's dead simple and from a recognized tutorial web page for ruby. I guess that the problem is my operating system, but how do I get it working properly?
Solution
Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.
A Simple Client:
require 'socket' # Sockets are in standard library
hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets # Read lines from the socket
puts line.chop # And print with platform line terminator
end
s.close
Now call TCPServer.open
hostname
, port
function to specify a port for your service and create a TCPServer object.
A Simple Server:
require 'socket' # Get sockets from stdlib
server = TCPServer.open(2000) # Socket to listen on port 2000
loop { # Servers run forever
client = server.accept # Wait for a client to connect
client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
}
read doc
Answered By - Зелёный Answer Checked By - Terry (WPSolving Volunteer)