如何在 python 中让客户端和服务器发送和接受不同的消息长度

How to make client and server send and accept different message lengths in python

在我的python作业中,我必须制作一个服务器和一些客户端。

我的问题来自服务器端和客户端的 packing/unpacking 进程中的固定字符串大小。我想用两个不同大小的字符串发送消息。

这是我的简化代码:

客户:

import socket
import struct


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect(('127.0.0.1', 5555))
    str1 = b"A"
    msg = (str1, 3)
    msg_packed = struct.Struct("1s I").pack(*msg) #the fixed string size is not a problem here
    sock.sendall(msg_packed)

    reply_packed = sock.recv(1024)
    reply = struct.Struct("2s I").unpack(reply_packed) #since the string in the reply can be 'Yes' or 'No' what is 2 and 3 character. I don't know hot make it accept both.
    print(reply)

和服务器:

import socket
import select
import struct


srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(('0.0.0.0', 5555))
srv.listen()

socks = [srv]


while True:
    readable, writeable, err = select.select(socks, [], [], 0.1)

    for s in readable:
        if s == srv:
            client, client_address = srv.accept()
            print("New client from: {} address".format(client_address))
            socks.append(client)
        else:
            msg_packed = s.recv(1024)
            if msg_packed:
                for sock in socks:
                    if sock == s and sock != srv:
                        msg = struct.Struct("1s I").unpack(msg_packed)

                        if (msg[0] == b'A'): #In here the reply message need to be 'Yes' or 'No'
                            reply = (b'Yes', msg[1] * msg[1])# the struct.Struct("2s I").pack(*reply) will not going to accept this
                        else:
                            reply = (b'No', msg[1] + msg[1])

                        reply_packed = struct.Struct("2s I").pack(*reply)
                        sock.send(reply_packed)
            else:
                print("Client disconnected")
                socks.remove(s)
                s.close()

有什么方法可以同时发送 2 和 3 字符串长度吗?如果是,我应该如何更改我的代码?

编辑:您可以动态设置结构的格式字符串。这是一个简单的例子:

str1 = b"Yes"
str2 = b"No"
msg_packed1 = struct.Struct("{}s".format(len(str1))).pack(str1)
msg_packed2 = struct.Struct("{}s".format(len(str2))).pack(str2)

在你的例子中是

reply_packed = struct.Struct("{}s I".format(len(reply[0]))).pack(*reply)

我的想法来自 packing and unpacking variable length array/string using the struct module in python