簡體   English   中英

如何使客戶端和服務器在 python 中發送和接受不同的消息長度

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

在我的 python 作業中,我必須制作一個服務器和一些客戶端。

我的問題來自服務器和客戶端的打包/解包過程中的固定字符串大小。 我想用兩個不同大小的字符串發送消息。

這是我的簡化代碼:

客戶:

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)

我從使用 python 中的 struct 模塊打包和解包可變長度數組/字符串中得到了這個想法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM