【问题标题】:Python client can not communicate with ruby server. I get [Errno 10061] No connection could be made because the target machine actively refused itPython 客户端无法与 ruby​​ 服务器通信。我得到 [Errno 10061] 无法建立连接,因为目标机器主动拒绝它
【发布时间】:2016-05-12 14:13:16
【问题描述】:

我打算对 Ruby on Rails 应用程序的数据库中的数据运行用 Python 编写的机器学习算法。经过一番研究,我发现了套接字,因此创建了一个 Ruby 服务器和 Python 客户端。我在两个不同的命令提示符终端上同时运行它们。

这是 Ruby 服务器代码:

require "socket"

server = TCPServer.open(2000)

loop {
  client = server.accept
  client.puts(Time.now.ctime)
  client.puts "Closing the connection. Bye!"
  client.close
  }

这是 Python 客户端代码:

import socket

s = socket.socket()
host = "localhost"
port = 2000
s.connect((host , port))

我不明白问题出在哪里。请协助。

【问题讨论】:

  • 两个程序是否在同一主机上运行?
  • 您的代码在这里没有问题。
  • 但是为什么要采用这种极其复杂的方法呢?为什么不只坚持红宝石?如果您不想使用 ruby​​,为什么不直接使用 python 连接到数据库?
  • 您的机器可以有多个网络地址(以太网/Wi-Fi 或 IPv4/IPv6),请确保两者使用相同。
  • @DisplayName by same host 你的意思是同一台电脑吗?如果是这样,那么是的。我在同一台计算机上有两个终端。

标签: python ruby server client


【解决方案1】:

鉴于我在代码 Ruby 服务器和 Python 客户端上面的问题的有见地的答案,应该如下所示。

对于 Ruby 服务器:

require "socket" # Get sockets from stdlib

server = TCPServer.open("127.0.0.1" , 2000) # Socket to listen on port 2000

loop {                     # Server runs 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

  }

对于 Python 客户端:

import socket # Import socket module

s = socket.socket() # Create a socket object
host = "127.0.0.1"
port = 2000 # Reserve a port for your service.
s.connect((host , port))
print s.recv(1024)
s.close() # Close the socket when done

Ruby 中 TCPServer 类的 open() 方法有两个参数。第一个是主机名,第二个是端口,即

TCPServer.open(hostname , port)

【讨论】:

    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2021-11-10
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多