Python 客户端-服务器(*缺乏理解)

Python client-server (*lack of understanding)

我遇到了一个挑战:

消息系统由 2 个组件组成 - 客户端和服务器。

3 种消息类型:

1) 用当前服务器时间响应

2) 响应到目前为止对服务器的调用次数(*自启动以来 运行)

3) 两数相乘

我尝试用 python 做到这一点,所以我看到了这个视频教程:

https://www.youtube.com/watch?v=WrtebUkUssc

并阅读本指南:

http://www.bogotobogo.com/python/python_network_programming_server_client.php

但是我很不理解,服务器怎么知道客户端要求什么?

以及服务器如何响应每个查询,我只能看到它接收到的字节是什么..

我希望有人能帮助我,我只有 24 小时来回答这个问题(这是对工作的挑战)

谢谢大家!!

如果我处于你的处境,我不会试图深入了解幕后发生的所有事情。

首先我会检查我应该达到的目标:

1) respond with current server time:

  • 已启动服务器并且 运行
  • 能够在某些路由(例如 /time)上通过 http GET 方法接收请求
  • 能够发送响应
  • 选择响应格式(json是一个不错的选择)
  • 了解您的数据在该格式下是否有效(对于 json,您可以使用 https://jsonlint.com/
  • 发送包含服务器时间的响应

2) respond with number of calls made to the server so far(*since it started running):

不清楚要求您做什么。也许服务器应该能够响应不止一次?

3) multiplication of two numbers:

  • 选择您将支持的 http 方法。如果您选择 http GET 客户端将必须在 url 中发送这些数字,例如 /multiply/2/3/。如果您选择 http POST,您将不得不发送在 url 中不可见的数据(也称为负载),例如 /multiply
  • 能够发送响应
  • 选择响应格式(json是一个不错的选择)
  • 了解您的数据在该格式下是否有效(对于 json,您可以使用 https://jsonlint.com/
  • 发送包含答案的响应(示例响应数据可能类似于 {"answer": 6}

先选择要编码的服务器。通过查看什么是 requestresponse、方法 GETPUTPOST 以及什么是 http status code 来了解一些关于 http 的知识。在编写代码时,您必须了解一些基本的 http 状态代码,例如 200404400。使用像 flask 这样简单的网络框架,这样你就不必处理 udp、tcp、套接字和其他不相关的东西。了解如何向您的服务器发出 http 请求。 curl 是一个不错的选择,但如果您想要其他东西,请确保您的客户端会向您显示响应状态代码、headers 和数据。最后但并非最不重要的一点是不要卡住,因为卡住会很快消耗你的时间。

您链接到的 article 为您提供了足够的信息来创建客户端和服务器来执行您的要求。

注意:此答案侧重于 HTTP 的原始套接字连接:请参阅@ŽilvinasRudžionis 的回答

how [does] the server knows what the client asking for?

事实并非如此。至少本质上不是。这就是为什么您需要编写代码以使其理解客户的要求。理解这一点的文章的最佳部分是 Echo Server 部分。

要开始理解,您需要遵循此示例。

# echo_server.py
import socket

host = ''                                  # Symbolic name meaning all available interfaces
port = 12345                               # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET,          # See [1]
                  socket.SOCK_STREAM) 
s.bind((host, port))                       # Server claims the port
s.listen(1)                                # See [2]
conn, addr = s.accept()                    # This is code halting, everything
                                           # will hold here and wait for a connection
print('Connected by', addr)

while True:
    data = conn.recv(1024)                # Receive 1024 bytes
    if not data: break                    # If data is Falsey (i.e. no data) break
    conn.sendall(data)                    # Send all data back to the connection
conn.close()

[1] [2]


# echo_client.py
import socket

host = socket.gethostname()               # Server is running on the same host
port = 12345                              # The same port as used by the server
s = socket.socket(socket.AF_INET,         # See server code ([1])
                  socket.SOCK_STREAM)
s.connect((host, port))                   # Initiate the connection
s.sendall(b'Hello, world')                # Send some bytes to the server
data = s.recv(1024)                       # Receive some bytes back
s.close()                                 # Close the connection
print('Received', repr(data))             # Print the bytes received

这为您提供了一个基本框架来查看正在发生的事情。从这里,您可以添加自己的代码来检查数据和连接。

最重要的部分是您在服务器上接受连接的部分。在这里,您可以检查收到的数据并做出适当的响应。对于 time,文章中的 first example 显示了如何执行此操作。

#--snip--
import time

# Receive all data
while True:
    data = conn.recv(1024)
    if not data: break

# Now we can check the data and prepare the response
if data == "TIME":
    return_data = (time.ctime(time.time()) + "\r\n").encode('ascii')
elif data == "REQUEST COUNT":
    # Code to get request count
elif "MULTI" in data:
    # Example: MULTI 2 3
    data = data.split(" ")  # Becomes ["MULTI", "2", "3"]
    # Code to multiply the numbers

# Send the result back to the client
conn.sendall(return_data)

我有 created a github gist 时间示例,您可以下载并使用。它应该适用于 Python 2 和 3。

<script src="https://gist.github.com/alxwrd/b9133476e2f11263e594d8c29256859a.js"></script>