簡體   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