使用Python中的套接字发送字典? [英] Sending a Dictionary using Sockets in Python?

查看:201
本文介绍了使用Python中的套接字发送字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

哦,如果你想知道TR值是什么。它是包含用于加密简单消息的翻译的字典。

Oh, and if your wondering what TRvalues is. It's the dictionary that contains the 'translations' for encrypting simple messages.

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中导入)

(The translations are held in a .txt it imports)

推荐答案

你必须序列化你的数据。有很多方法可以实现,但 json pickle 将是他们进入标准库的可能方式。

You have to serialize your data. there would be many ways to do it, but json and pickle will be the likely way to go for they being in standard library.

for json:

import json

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

对于泡菜(或其更快的兄弟姐妹 cPickle ):

for pickle(or its faster sibling 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

因为简单的而True:就足够了。

这篇关于使用Python中的套接字发送字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆