繁体   English   中英

在Python中使用套接字发送字典?

[英]Sending a Dictionary using Sockets in Python?

我的问题:好的,我做了一个小聊天程序,我基本上使用套接字来通过网络发送消息。

它工作得很好,但当我决定更进一步时,我遇到了一个问题。

我决定在我通过网络发送的字符串中添加一些加密,所以我继续编写了执行该操作的脚本。

问题是,显然你不能像通过字符串一样通过套接字发送字典。

我先做了一些研究,然后我找到了关于泡菜的东西。 不幸的是,除了将字典导出到文件之外,我无法确切地知道如何使用它们来转换字符串,但如果不更改我的程序,我就无法做到这一点。

任何人都可以帮助解释我是如何做到这一点的吗? 我到处都看了看,但我似乎无法弄清楚如何。

我已经上传了迄今为止我所拥有的内容,如果有任何人感兴趣的话。

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")

哦,如果你想知道什么是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)

(翻译保存在.txt导入中)

您必须序列化您的数据。 有很多方法可以做到这一点,但jsonpickle将成为他们在标准库中的可能方式。

为json:

import json

data_string = json.dumps(data) #data serialized
data_loaded = json.loads(data) #data loaded

对于泡菜(或其更快的兄弟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.

另外,请不要写

i= True
while i is True:
 #do_something

因为简单while True:就足够了。

您需要先将序列化数据。 有几种方法可以做到这一点,最常见的可能是JSON,XML和(特定于python)泡菜。 或者您自己的自定义序列化。

基本思想是:序列化您的数据,发送,接收,再次反序列化。

如果要使用pickle,可以使用loadsdumps功能。

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)

您也可以以类似的方式使用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)

您可以使用pickle和python远程对象(或仅pyro),通过网络发送完整的对象和数据(包括Internet)。 例如,如果您想要发送对象(字典,列表,类,对象等),请使用python远程对象。

它对你想做的非常有用。

此链接中提供了更多信息http://pythonhosted.org/Pyro4/此入门手册可用于了解您在网络电脑上发送或执行的内容http://pythonhosted.org/Pyro4/intro.html#simple-例

我希望它会对你有所帮助

使用JSON来序列化数据是我喜欢的方式。 我实际上创建了一个可以为你做到这一点的库jsonsocket库 它会自动为您进行序列化/反序列化。 它还可以有效地处理大量数据。

您还可以使用zmqObjectExchanger( https://github.com/ZdenekM/zmq_object_exchanger )。 它包装pickle和zmq以通过网络传输python对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM