在Python中通过套接字发送字典?

14 投票
6 回答
50628 浏览
提问于 2025-04-17 17:47

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

这个程序运行得很好,但当我想进一步改进时,遇到了一个问题。

我决定给我发送的字符串加上一些加密,所以我写了一个脚本来实现这个功能。

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

我先做了一些研究,发现了关于Pickles的资料。不幸的是,我没能找到具体如何使用它们来转换字符串的方法,除了把字典导出到一个文件,但我不能在不改变程序的情况下这样做。

有没有人能帮我解释一下该怎么做?我到处找过,但似乎找不到答案。

我把目前的进展上传到这里,如果有人感兴趣的话。

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文件里)

6 个回答

4

如果你想使用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)
5

你需要先把你的数据进行“序列化”。这有几种方法,最常见的可能是 JSON、XML 和(专门针对 Python 的)pickles,或者你自己定义的序列化方式。

简单来说,就是:把数据转换成一种可以发送的格式,发送出去,接收后再把它转换回原来的格式。

29

你需要把你的数据进行序列化。序列化就是把数据转换成一种可以存储或传输的格式。有很多种方法可以做到这一点,但最常用的方式是使用jsonpickle,因为它们都是标准库里自带的。

对于json:

import json

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

对于pickle(或者它的更快版本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:就足够了。

撰写回答