0

我正在尝试我的 PC 和 Raspberry Pi 4 之间的 pyro4 连接。我的 PC
上的代码是:

# saved as server.py
import Pyro4, Pyro4.naming
import socket, threading

# Define an object that will be accessible over the network.
# This is where all your code should go...
@Pyro4.expose
class MessageServer(object):
    def show_message(self, msg):
        print("Message received: {}".format(msg))


# Start a Pyro nameserver and daemon (server process) that are accessible
# over the network. This has security risks; see
# https://pyro4.readthedocs.io/en/stable/security.html
hostname = socket.gethostname()
ns_thread = threading.Thread(
    target=Pyro4.naming.startNSloop, kwargs={'host': hostname}
)
ns_thread.daemon = True   # automatically exit when main program finishes
ns_thread.start()
main_daemon = Pyro4.Daemon(host=hostname)

# find the name server
ns = Pyro4.locateNS()
# register the message server as a Pyro object
main_daemon_uri = main_daemon.register(MessageServer)
# register a name for the object in the name server
ns.register("example.message", main_daemon_uri)

# start the event loop of the main_daemon to wait for calls
print("Message server ready.")
main_daemon.requestLoop()

我的树莓上的代码是:

import Pyro4
import sys

print("Message:")
msg=sys.stdin.readline().strip()

message_server = Pyro4.Proxy("PYRONAME:192.168.1.5")
message_server.show_message(msg)

我电脑上的代码没有显示任何错误,但是当我尝试从树莓派发送消息时,我得到了这个:

What s your message?
test
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 102, in getIpAddress
    return getaddr(config.PREFER_IP_VERSION) if ipVersion is None else getaddr(ipVersion)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 94, in getaddr
    ip = socket.getaddrinfo(hostname or socket.gethostname(), 80, family, socket.SOCK_STREAM, socket.SOL_TCP)[0][4][0]
  File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 515, in connect_and_handshake
    sslContext=sslContext)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 266, in createSocket
    if getIpVersion(connect[0]) == 4:
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 68, in getIpVersion
    address = getIpAddress(hostnameOrAddress)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 106, in getIpAddress
    return getaddr(0)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/socketutil.py", line 94, in getaddr
    ip = socket.getaddrinfo(hostname or socket.gethostname(), 80, family, socket.SOCK_STREAM, socket.SOL_TCP)[0][4][0]
  File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/pi/Desktop/client.py", line 10, in <module>
    message_server.show_message(msg)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 275, in __getattr__
    self._pyroGetMetadata()
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 615, in _pyroGetMetadata
    self.__pyroCreateConnection()
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 588, in __pyroCreateConnection
    uri = _resolve(self._pyroUri, self._pyroHmacKey)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 1915, in _resolve
    return nameserver.lookup(uri.object)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 275, in __getattr__
    self._pyroGetMetadata()
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 615, in _pyroGetMetadata
    self.__pyroCreateConnection()
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 596, in __pyroCreateConnection
    connect_and_handshake(conn)
  File "/home/pi/.local/lib/python3.7/site-packages/Pyro4/core.py", line 549, in connect_and_handshake
    raise ce
Pyro4.errors.CommunicationError: cannot connect to ('JAKOB-PC', 9090): [Errno -2] Name or service not known

我的电脑禁用了防火墙,所以应该没有任何问题。我的本地 IP 是 192.168.1.5。我正在使用无头树莓并使用 puTTY 和 VNC 在其上编写代码。

我已经用谷歌搜索了这个错误,但找不到任何答案。任何帮助,将不胜感激。

4

2 回答 2

1

我做了这个

#
# Server.py
#
from __future__ import print_function
import Pyro4


@Pyro4.expose
@Pyro4.behavior(instance_mode="single")
class Messenger(object):
    # This is a constructor
    def __init__(self):
        pass

    # This method will be called on the server
    def send_message(self, name, message):
        print("[{0}] {1}".format(name, message))


def main():
    Pyro4.Daemon.serveSimple(
        {
            Messenger: "example.messenger"
        },
        ns=True)


if __name__ == "__main__":
    main()
#
# Client.py
#

# This is the code that visits the warehouse.
import sys

import Pyro4
import Pyro4.util


sys.excepthook = Pyro4.util.excepthook

messenger = Pyro4.Proxy("PYRONAME:example.messenger@192.168.1.5")
messenger.send_message("Tim", "Hello!")

然后跑了

  • python -m Pyro4.naming -n 192.168.1.5
  • python Server.py
  • python Client.py
于 2020-07-17T11:09:14.610 回答
0

简而言之,我无法用 Pyro 解决问题,而且(几乎)没有人帮忙,所以我决定改用“websockets”。

你可以在这里阅读文档, 但无论如何我都会在这里解释。

首先,您需要两台具有网络连接的设备。您还必须在它们两个上运行 python 3.6.1。之后,如果您还没有安装 websocketspip install websockets或者我必须使用pip3 install websockets.

下面的代码在服务器上运行并处理您从客户端发送给它的消息。函数 'hello' 是处理请求和发回响应的简单示例。'request' 是服务器接收的数据,该数据必须是字节,可迭代的字符串。通过将请求转换为整数、对其进行平方并将其转换回字符串来做出响应。然后将此响应发送回客户端。'start_server' 定义服务器,定义其行为的函数(hello),服务器运行的 IP 地址(192.168.1.117)和它将接收请求的端口(8765)。

!/usr/bin/env python

import asyncio
import websockets

print("Running...")

async def hello(websocket, path):
    request = await websocket.recv()
    print("Request: " + request)

    response = str(int(request)*int(request))

    await websocket.send(response)
    print("Response:" + response)

start_server = websockets.serve(hello, "192.168.1.117", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

下一位是客户端上的代码。'uri' 是服务器的 ip 和端口。函数“tellServ”要求您输入一些数据(“tell”变量)并将其发送到服务器。之后它等待回复,一旦得到它就会打印出来。在这种情况下,如果我输入数字“6”,服务器会回复“36”。函数循环处于 while 循环中,因此我可以发送多个数字而无需重新启动脚本。

#!/usr/bin/env python

import asyncio
import websockets

uri = "ws://192.168.1.117:8765"

async def tellServ():
    async with websockets.connect(uri) as websocket:
        tell = input("Podatek ki ga posles: ")
        await websocket.send(tell)

        reply = await websocket.recv()
        print("Odgovor:")
        print(reply)
while 1:
    asyncio.get_event_loop().run_until_complete(tellServ())
于 2020-09-17T08:15:21.983 回答