通过 python 连接到 Google 云服务器

Connect to Google cloud server via python

我想将我的笔记本电脑(后来是树莓派 pi/Jetson nano)连接到服务器。目标是能够将数据发送到服务器,然后对其进行处理和评估,并将输出(GPS 坐标)发送回客户端(laptop/raspberry pi/Jetson nano)。 理想情况下,我只需将 Google 服务器的 public IP 地址插入客户端的 运行 代码中,然后连接到服务器。

但是,运行宁服务器代码:

import socket

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

和客户端代码:

import socket

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 65432        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))

提供者:https://realpython.com/python-sockets/ .

将仅使用默认的本地 IP 地址,否则会 returns 找不到 IP 地址错误。

编辑:答案更倾向于通过 google 云 API 进行互联网连接。该解决方案完美地说明了这一点,但是我的问题不够明确抱歉!

有很多方法可以做到这一点,但我建议使用 GCE 实例作为您的服务器,或者使用 App Engine 部署。 Cloud 运行 和 Cloud Functions 也可以。 (编辑: 忘记了 k8s)

请注意,使用 GCE 实例时,您需要根据 documentation 打开防火墙。

另请注意,除非您为 GCE 实例分配静态 IP 地址,否则它将是短暂的。如果您使用 App Engine,您可以只使用 https://project-id.appspot.com/ 作为客户端中的服务器地址。

您需要使用 Flask、FastAPI 或其他网络应用程序框架设置一个简单的网络服务器。使用简单的框架会让生活更轻松,因为它会减轻您的负担。

您可以让您的客户端使用它需要作为参数发送的数据来执行请求,并让网络应用程序执行魔术并提供响应。我强烈建议 return 一个 JSON 响应,因为这或多或少是 API 的标准。 (您的网络应用程序基本上就是这样)。另外,您可能知道,JSON 很容易转换为 python.

中可用的东西

请参阅下面这个非常简单的示例。

服务器代码

from flask import Flask, request
import json


app = Flask(__name__)
longitude_divisor = 0.004167


@app.route("/api/gettimediff")
def gettimediff():
    longitude = float(request.args.get("Longitude"))
    # http://www.cs4fn.org/mobile/owntimezone.php
    seconds = longitude / longitude_divisor
    response = json.dumps({"seconds": seconds}, indent=4)
    return response


@app.route("/api/switch")
def switch():
    longitude = float(request.args.get("Longitude"))
    latitude = float(request.args.get("Latitude"))
    response = json.dumps({"Latitude": longitude, "Longitude": latitude})
    return response


if __name__ == "__main__":
    # This is used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    # Flask's development server will automatically serve static files in
    # the "static" directory. See:
    # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
    # App Engine itself will serve those files as configured in app.yaml.
    app.run(host="127.0.0.1", port=8080, debug=True)

客户代码

import requests
import json


serveraddress = "http://127.0.0.1:8080/"
data = {"Latitude": 48.85837, "Longitude": 2.294481}


print("switch")
response = requests.get(
    f"{serveraddress}api/switch", 
    params=data
)
print(data)
print(response.text)

print("seconds")
response = requests.get(
    f"{serveraddress}api/gettimediff", 
    params=data
)
print(data)
print(response.text)
converted = json.loads(response.text)
print(converted)