如何在文本文件中一个接一个延迟地发送字符串?

时间:2019-06-29 09:04:43

标签: python string file sockets

我有一个客户端服务器连接,该连接加密了文本文件中的字符串。客户端打开.txt文件,对那些字符串进行加密并将其发送到服务器。我在.txt文件中得到3个字符串,并希望将加密的字符串一个接一个地发送到服务器。

因此,客户端应该发送X字符串(在发送Y字符串之前等待1秒钟),与此同时,服务器将解密后的字符串返回给客户端。 这就是我要通过套接字发送数据的原因

inFile = open("textinput.txt", "rb")
content = inFile.read()
inFile.close()

enc_data = publickey.encrypt(content, 16)

ipaddr = "127.0.0.1"
portnr = 11200

connectie = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connectie.connect((ipaddr, portnr))
connectie.send(enc_data[0])#send encrypted data

content包含3个字符串,enc_data包含3个字符串,但已加密。我使用enc_data

connectie.send发送到服务器

我如何能够延迟1秒分别发送这些字符串?

1 个答案:

答案 0 :(得分:1)

演示了简化的自定义加密/解密方法(使用simple-crypt库):

示例input.txt的内容:

first line
second line
last line

server.py

import socket
from simplecrypt import encrypt, decrypt

HOST = '127.0.0.1'
POST = 11200

pwd = 'secret' # for demo only

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind((HOST, POST))
    sock.listen(1)

    conn, addr = sock.accept()
    with conn:
        print(f'Got connection from {addr}')
        while True:
            data = conn.recv(1024)
            if not data:
                break
            print(f'Received data from client {data}')
            conn.send(decrypt(pwd, data))

client.py

import socket
from simplecrypt import encrypt, decrypt
import time

HOST = '127.0.0.1'
POST = 11200

pwd = 'secret' # for demo only

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect((HOST, POST))
    with open('input.txt', 'rb') as f:
        for line in f:
            sock.send(encrypt(pwd, line.strip()))
            time.sleep(1)   # the needed delay
            data = sock.recv(1024).decode('utf8')
            print(f'Received data from server "{data}"')

套接字服务器进程的运行和输出:

[roman@roman-pc data]$ python3 server.py
Got connection from ('127.0.0.1', 40736)
Received data from client b"sc\x00\x02p\x02\x98\xd4@\x9e\xeaeb@u\xc5\xbc\x0b\xbea\xcf\xca~\x87\xb1\x01(\x9d\xd2\x05\x0b8\xa8\x85\x94\xc4\xc5\xe2W\x8d\xe5P\xec\x83D\xeb\xe8\xcbV\x1ai3\xf5\x13s\x82\xbe7\xc9\xa8\xad'e\xbeq&Q_\x0f\t~V\x13\xe9\xde\xf1\xba~"
Received data from client b'sc\x00\x02Sa\xe9\x97,\xf7\x99\x7f<\xd2n\xbfc\x98g~t\xa3\xf9\x98\xc9\xf9\xff>\x99\x9aI{sAMY"\x9bX\x19\xfe\xe3i\xad=\xfa\rs\x9b,\xaadN\xb9_Bc\xe2\xf75\xdfP/wx\x1a\x91\xa27VZ[M\xa3\x0f3\xc9vL'
Received data from client b'sc\x00\x02U\xb8\xbc|\xbb\xbe\x95\xd5\\}0}\x8a\x10^]\xa0\xc9S\x08a\x99\x8e\xdd7[\xa4q\xec|\xe3\xe1\xf9|\xca?\x07\x18\xbc\xb4^*`\x7f\x07)\x1b\x10&\xda\xfdl!O\xa5K\xbe.\xd4\xbe\xb0\x960\x81\x83\xcb\x07\xb0=\x95\x8f\xd5\xb5'

套接字客户端进程的运行和输出(以所需的延迟发送加密的消息):

[roman@roman-pc data]$ python3 client.py
Received data from server "first line"
Received data from server "second line"
Received data from server "last line"