在 Python 中使用套接字发送字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15190362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending a Dictionary using Sockets in Python?
提问by Micrified
My problem: Ok, I made a little chat program thing where I am basically using sockets in order to send messages over a network.
我的问题:好的,我做了一个小聊天程序,我基本上使用套接字来通过网络发送消息。
It works great, but when I decided to take it a step further, I ran into a problem.
它工作得很好,但是当我决定更进一步时,我遇到了一个问题。
I decided to add some encryption to the strings I was sending over the network, and so I went ahead and wrote the script that did that.
我决定为我通过网络发送的字符串添加一些加密,所以我继续编写了执行此操作的脚本。
The problem is that apparently you can't just send a dictionary through sockets as you might with a string.
问题是,显然您不能像使用字符串一样通过套接字发送字典。
I did some research first, and I found this stuff about Pickles. Unfortunately, I couldn't find out exactly how I could use them to convert strings, aside from having it exporting the dictionary to a file, but I can't do that without changing my program.
我先做了一些研究,我发现了关于泡菜的这些东西。不幸的是,除了将字典导出到文件之外,我无法确切地找出如何使用它们来转换字符串,但是如果不更改我的程序,我就无法做到这一点。
Can anyone help explain how I am to do this? I've looked around everywhere but I can't seem to find out how.
任何人都可以帮助解释我如何做到这一点?我到处环顾四周,但似乎无法找到方法。
I've uploaded what I've got so far here, if that comes of any interest to anybody.
如果有人对此感兴趣,我已经上传了到目前为止的内容。
print("\n\t\t Fill out the following fields:")
HOST = input("\nNet Send Server Public IP: ")
PORT = int(input("\nNet Send Server Port: "))
#------------------------------------------------
#Assessing Validity of Connection
#------------------------------------------------
try:
s = socket(AF_INET,SOCK_STREAM)
s.connect((HOST,PORT))
print("Connected to server:",HOST,)
except IOError:
print("\n\n\a\t\tUndefined Connection Error Encountered")
input("Press Enter to exit, then restart the script")
sys.exit()
#-------------------------------------------------
#Now Sending and recieving mesages
#-------------------------------------------------
i = True
while i is True:
try:
User_input = input("\n Enter your message: ")
Lower_Case_Conversion = User_input.lower()
#Tdirectory just stores the translated letters
Tdirectory = []
# x is zero so that it translates the first letter first, evidently
x = 0
COUNTLIMIT = len(Lower_Case_Conversion)
while x < COUNTLIMIT:
for letter in Lower_Case_Conversion[x]:
if letter in TRvalues:
Tdirectory += [TRvalues[Lower_Case_Conversion[x]]]
x = x + 1
message = input('Send: ')
s.send(message.encode())
print("\n\t\tAwaiting reply from: ",HOST,)
reply = s.recv(1024)
print(HOST,"\n : ",reply)
except IOError:
print("\n\t\aIOError Detected, connection most likely lost.")
input("\n\nPress Enter to exit, then restart the script")
Oh, and if your wondering what TRvalues is. It's the dictionary that contains the 'translations' for encrypting simple messages.
哦,如果您想知道 TRvalues 是什么。它是包含用于加密简单消息的“翻译”的字典。
try:
TRvalues = {}
with open(r"C:\Users\Owatch\Documents\Python\FunStuff\nsed.txt", newline="") as f:
reader = csv.reader(f, delimiter=" ")
TRvalues = dict(reader)
(The translations are held in a .txt it imports)
(翻译保存在它导入的 .txt 中)
采纳答案by thkang
You have to serialize your data. there would be many ways to do it, but jsonand picklewill be the likely way to go for they being in standard library.
您必须序列化您的数据。有很多方法可以做到这一点,但是json和pickle将是他们在标准库中的可能方法。
for json :
对于 json :
import json
data_string = json.dumps(data) #data serialized
data_loaded = json.loads(data) #data loaded
for pickle(or its faster sibling cPickle):
对于泡菜(或其更快的兄弟cPickle):
import cPickle as pickle
data_string = pickle.dumps(data, -1)
#data serialized. -1, which is an optional argument, is there to pick best the pickling protocol
data_loaded = pickle.loads(data) #data loaded.
also, please don't write
还有,请不要写
i= True
while i is True:
#do_something
because simple while True:would suffice.
因为简单while True:就足够了。
回答by Hyperboreus
You need to serialize your data first. There are several ways to do this, the most common probably JSON, XML and (python specific) pickles. Or your own custom serialization.
您需要先序列化您的数据。有几种方法可以做到这一点,最常见的可能是 JSON、XML 和(python 特定的)泡菜。或者您自己的自定义序列化。
The basic idea is: Serialize your data, send it, receive it, deserialize it again.
基本思想是:序列化您的数据,发送,接收,再次反序列化。
回答by djhoese
If you want to use pickle you can use the loadsand dumpsfunctions.
如果你想使用泡菜,你可以使用loads和dumps函数。
import pickle
a_dict = { x:str(x) for x in range(5) }
serialized_dict = pickle.dumps(a_dict)
# Send it through the socket and on the receiving end:
a_dict = pickle.loads(the_received_string)
You can also use JSON in a similar fashion. I like JSON because it is human readable and isn't python specific.
您也可以以类似的方式使用 JSON。我喜欢 JSON,因为它是人类可读的,并且不是特定于 Python 的。
import json
a_dict = { x:str(x) for x in range(5) }
serialized_dict = json.dumps(a_dict)
# Send it through the socket and on the receiving end:
a_dict = json.loads(the_received_string)
回答by ManuParra
You can use pickle and python remote object (or pyro only), to send full objects and data over networks (Internet included). For instance, if you want send object (dict, list, class, objects, etc. ) use python remote objects for it.
您可以使用pickle 和python 远程对象(或仅限pyro),通过网络(包括Internet)发送完整的对象和数据。例如,如果您想发送对象(字典、列表、类、对象等),请使用 python 远程对象。
It very useful for you want to do.
它对你想做的事情非常有用。
There is more information in this link http://pythonhosted.org/Pyro4/And this starter manual can be useful to know what you send or execute on network pcs http://pythonhosted.org/Pyro4/intro.html#simple-example
此链接中有更多信息http://pythonhosted.org/Pyro4/并且此入门手册可用于了解您在网络 pc 上发送或执行的内容http://pythonhosted.org/Pyro4/intro.html#simple-例子
I hope it will help you
我希望它会帮助你
回答by Mouad Debbar
Using JSON to serialize your data is the way I prefer to do it. I actually made a library that does just that for you: jsonsocket library. It will do the serialization/deserialization automatically for you. It also handles big amounts of data efficiently.
使用 JSON 序列化您的数据是我更喜欢的方式。我实际上为你做了一个库:jsonsocket library。它将自动为您执行序列化/反序列化。它还可以有效地处理大量数据。
回答by ZdenekM
You can also use zmqObjectExchanger (https://github.com/ZdenekM/zmq_object_exchanger). It wraps pickle and zmq to transfer python objects over network.
您还可以使用 zmqObjectExchanger ( https://github.com/ZdenekM/zmq_object_exchanger)。它包装了 pickle 和 zmq 以通过网络传输 python 对象。

