我对套接字和泡菜有疑问。值不会保存到 txt 中

I have a problem with socket and pickles. Values ​do not save to in txt

我的 Python 代码的想法是从网络套接字中读取值,并使用 pickles 将值保存在 txt 文件中,以供以后在另一个应用程序中使用。

不一定非得是txt文件,但这是我正在尝试使用的文件。

沟通很好,他创建了txt文件,可惜没有记录任何东西。

有人可以帮助我。 谢谢

服务器代码:

import socket
import pickle


HOST = ''              
PORT = 5000            
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (HOST, PORT)
tcp.bind(orig)
tcp.listen(10)
filename = 'data.txt'


while True:
    con, cliente = tcp.accept()
    print('connector by', cliente)
    while True:
        msg = con.recv(4096)
        if not msg: break
        print(msg)

    with open(filename, 'wb') as f:
        pickle.dumps(msg, f)

    print('Ending client connection', cliente)
    con.close()

客户代码:

import socket


HOST = '10.0.0.120'
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (HOST, PORT)
tcp.connect(dest)

print('to exit press CTRL+C\n')
msg = input()
while msg != '\x18':
    msg = input()
    tcp.sendall(msg.encode('utf8'))


tcp.close()

这里:

while True:
        msg = con.recv(4096)
        if not msg: break
        print(msg)

with open(filename, 'wb') as f:
        pickle.dumps(msg, f)

打开文件的代码当且仅当 bool(msg) is False 时才到达,因为这是 while True 循环终止的时间,如此处所述:if not msg: break.

所以msg == '',最后写的是空字符串

你用错了方法。 pickle.dumps 生成字符串, 接受文件参数。实际上,您应该从该代码中得到一个例外:

TypeError: an integer is required (got type _io.BufferedWriter)

如果您将代码更改为使用 pickle.dump,它可以正常工作,因为这是转储到文件的正确方法。这是一个演示它工作的示例(不需要套接字,因为这是关于 pickle 的工作方式,而不是网络)。

import pickle

foo = b'Some test string'
print("Pickling string '{}'".format(foo))

with open("/tmp/test.pickle", "wb") as tfile:
    pickle.dump(foo, tfile)

with open("/tmp/test.pickle", "rb") as tfile:
    bar = pickle.load(tfile)

print("Reloaded string '{}'".format(bar))
# Confirm they're identical
assert foo == bar