1
最近,Iv'e一直在試圖編寫一個簡單的TCP服務器,以便以後構建到聊天室中。但每次我啓動服務器(server.rb
),然後我嘗試使用客戶端(client.rb
)我得到這個錯誤:Ruby TCP聊天服務器
[email protected] C:\Users\Sam\Documents\Coding
> client.rb
C:/Users/Sam/Documents/Coding/client.rb:6:in `initialize': No connection could be made because the target machine actively refused it. - connect(2) for "localhost" port 2001 (Errno::ECONNREFUSED)
from C:/Users/Sam/Documents/Coding/client.rb:6:in `open'
from C:/Users/Sam/Documents/Coding/client.rb:6:in `<main>'
我使用CMD運行此,我已經試過關掉防火牆簡單。 下面是這兩個程序的代碼...
這是server.rb
require 'socket'
server = TCPServer.open(2000) # Socket to listen on port 2000
loop {
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime) # Send time to the client
client.puts "Closing connection. Bye!"
client.close
end
}
這裏的client.rb
:
require 'socket'
hostname = "localhost"
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets # Reads lines from socket
puts line.chop # And print with platform line terminator
end
s.close # Close socket when done
(此代碼是從http://www.tutorialspoint.com/ruby/ruby_socket_programming.htm只是讓你知道)