2016-04-23 239 views
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只是讓你知道)

回答

0

我猜有2個選項:

  1. client.rb之前運行您的server.rb
  2. 您確定這些文件與您正在運行的文件完全相同。由於錯誤消息說它無法連接到端口2001,而在這兩個文件中它們都指2000。是否有可能編輯並運行不同的文件?你會感到驚訝,這是多麼普遍這是因爲:)