[英]How to send 2 variables from a client to the server at the same time using sockets [Python]
Client.py客户端.py
import socket
HOST = '127.0.0.1'
PORT = 65432
ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789.'
message = 'This message is encrypted using Caesar cipher'
def encryptstr(message,key):
#creating a list for new letters
newletters = []
#loop to assign new letter value
for letter in message:
uppercase = letter.isupper()
letter = letter.lower()
#checking if the letter is upper or lower
if letter in ALPHABET:
index = ALPHABET.find(letter)
newindex = (index + key) % len(ALPHABET)
letter = ALPHABET[newindex]
if uppercase:
letter = letter.upper()
newletters.append(letter)
#joining the list
return ''.join(newletters)
def findkey():
return 10
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
test = encryptstr(message, findkey())
s.sendall(test.encode()) # How to send key of 10 and Message?
data = s.recv(1024)
print('Received', data.decode())
Server.py服务器.py
import socket
HOST = '127.0.0.1'
PORT = 65432
ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789.'
def decryptstr(message,key):
#creating a list for new letters
newletters = []
#loop to assign new letter value
for letter in message:
uppercase = letter.isupper()
letter = letter.lower()
#checking if the letter is upper or lower
if letter in ALPHABET:
index = ALPHABET.find(letter)
newindex = (index - key) % len(ALPHABET)
letter = ALPHABET[newindex]
if uppercase:
letter = letter.upper()
newletters.append(letter)
#joining the list
return ''.join(newletters)
def findkey():
return 10
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
message = str(data.decode())
test = decryptstr(message, findkey())
print(test)
if not data:
break
conn.sendall(data)
What I am trying to do with this current code is from the server.我试图用这个当前代码做的是来自服务器。 I wish to send the variable of "10" to the client.
我希望将变量“10”发送给客户端。 From the client to the server, I would like to send back two variables, one being "10" and the other being the encrypted message.
从客户端到服务器,我想发回两个变量,一个是“10”,另一个是加密消息。 After both are sent, I would like the server to decrypt the message and print it on the screen.
两者都发送后,我希望服务器解密消息并将其打印在屏幕上。
You may be wondering why I would send the ten back and forth, and this is because I will be incorporating this Diffie-Hellman Example with the def findkeys()
, Thank you for your time!您可能想知道为什么我会来回发送 10 个,这是因为我将把这个Diffie-Hellman 示例与
def findkeys()
结合起来,谢谢您的宝贵时间!
client...客户...
sock.send(b'10'+encrypted_message)
server服务器
msg = sock.recv(1024)
code = msg[:2]
encrypted_payload = msg[2:]
Is this what you mean?你是这个意思吗?
You can send that var in json instead of single var it could help you to send more then 1 data at same time您可以在 json 中发送该 var 而不是单个 var 它可以帮助您同时发送超过 1 个数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.