le_*_*_me 1 ruby sockets tcp fedora
我在Fedora 20上使用ruby 2.1.0.我从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
Run Code Online (Sandbox Code Playgroud)
Ruby抛出以下错误:
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>'
Run Code Online (Sandbox Code Playgroud)
这次失败的原因是什么?我的意思是,代码应该明确地工作,它很简单,并且来自一个公认的ruby教程网页.我想这个问题是我的操作系统,但我怎样才能让它正常工作?
套接字是双向通信信道的端点.套接字可以在进程内,同一台机器上的进程之间或不同大洲的进程之间进行通信.
一个简单的客户:
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
Run Code Online (Sandbox Code Playgroud)
现在调用TCPServer.open hostname,port函数指定服务的端口并创建TCPServer对象.
简单的服务器:
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
}
Run Code Online (Sandbox Code Playgroud)
阅读文档
| 归档时间: |
|
| 查看次数: |
1076 次 |
| 最近记录: |