我的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()
最佳答案
您使用了错误的方法。 pickle.dumps
生成一个字符串,不接受文件参数。事实上,您应该从该代码中得到一个异常:
类型错误:需要一个整数(获取类型 _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
关于python - 我的 socket 和 pickle 有问题。值不保存到 txt 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58347683/