gpt4 book ai didi

Python:通过套接字发送的消息大小

转载 作者:太空狗 更新时间:2023-10-30 02:44:53 25 4
gpt4 key购买 nike

我正在尝试使用 socket 库发送消息。由于消息的大小可变,我决定在字符串的开头附加消息的大小,然后发送它。例如,如果消息是

Hello World!

长度为 13 个字符(我已经计算过 EOL),我会发送类似的内容

sizeof13charsinbytes|Hello World!

通过 socket.send(),然后我将使用 str.split()

拆分大小和消息

由于 socket.recv() 需要以字节为单位的消息大小,如何找到消息的大小?我尝试了 sys.getsizeof() 但它为单字符字符串提供了任意值。尺寸合适吗?

最佳答案

重新发明轮子没有意义。通过使用 multiprocessing.connection 模块将字符串作为 python 字符串对象发送,可以轻松发送可变长度字符串。此方法将允许发送大多数 python 对象,而不仅仅是字符串。

import multiprocessing
import multiprocessing.connection as connection

def producer(data, address, authkey):
with connection.Listener(address, authkey=authkey) as listener:
with listener.accept() as conn:
print('connection accepted from', listener.last_accepted)
for item in data:
print("producer sending:", repr(item))
conn.send(item)


def consumer(address, authkey):
with connection.Client(address, authkey=authkey) as conn:
try:
while True:
item = conn.recv()
print("consumer received:", repr(item))
except EOFError:
pass

listen_address = "localhost", 50000
remote_address = "localhost", 50000
authkey = b'secret password'

if __name__ == "__main__":
data = ["1", "23", "456"]
p = multiprocessing.Process(target=producer, args=(data, listen_address, authkey))
p.start()
consumer(remote_address, authkey)
p.join()
print("done")

产生类似的东西:

producer sending: '1'
producer sending: '23'
consumer received: '1'
producer sending: '456'
consumer received: '23'
consumer received: '456'
done

关于Python:通过套接字发送的消息大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27428936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com