Mic*_*ied 7 python sockets dictionary translation
我的问题:好的,我做了一个小聊天程序,我基本上使用套接字来通过网络发送消息.
它工作得很好,但当我决定更进一步时,我遇到了一个问题.
我决定在我通过网络发送的字符串中添加一些加密,所以我继续编写了执行该操作的脚本.
问题是,显然你不能像通过字符串一样通过套接字发送字典.
我先做了一些研究,然后我找到了关于泡菜的东西.不幸的是,除了将字典导出到文件之外,我无法确切地知道如何使用它们来转换字符串,但是如果不更改我的程序,我就无法做到这一点.
任何人都可以帮助解释我是如何做到这一点的吗?我到处都看了看,但我似乎无法弄清楚如何.
我已经上传了迄今为止我所拥有的内容,如果有任何人感兴趣的话.
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")
Run Code Online (Sandbox Code Playgroud)
哦,如果你想知道什么是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)
Run Code Online (Sandbox Code Playgroud)
(翻译保存在.txt导入中)
thk*_*ang 18
您必须序列化您的数据.有很多方法可以做到这一点,但json和pickle将成为他们在标准库中的可能方式.
为json:
import json
data_string = json.dumps(data) #data serialized
data_loaded = json.loads(data) #data loaded
Run Code Online (Sandbox Code Playgroud)
对于泡菜(或其更快的兄弟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.
Run Code Online (Sandbox Code Playgroud)
另外,请不要写
i= True
while i is True:
#do_something
Run Code Online (Sandbox Code Playgroud)
因为简单while True:
就足够了.
您需要首先序列化您的数据。有多种方法可以做到这一点,最常见的可能是 JSON、XML 和(Python 特定的)pickles。或者您自己的自定义序列化。
基本思想是:序列化你的数据,发送它,接收它,再次反序列化它。
归档时间: |
|
查看次数: |
29401 次 |
最近记录: |