保持套接字打开,直到客户端终止

时间:2018-12-28 19:18:04

标签: python sockets

我正在将用户输入许可证密钥(客户端)传递给验证(服务器),该验证将用户输入映射到我的许可API中的有效许可证。我需要服务器连接保持打开状态,直到客户端发送正确的许可证-可能在3次尝试后关闭连接。当我打开服务器套接字时,它会在收到来自客户端的第一个输入时关闭-无论请求是好是坏。如何仅在成功验证后关闭连接?

我尝试将验证检查包装在一个循环中,但这变得递归,因为当用户单击客户端上的tkinter按钮上的提交时,我们需要用户启动验证检查。

import requests
from xml.etree import ElementTree as ET
import socket

key = '***'
secret = '***'
request_type = {'Content-type': 'text/xml', 'Accept': 'text/xml'}
productURL = 'https://'+key+':'+secret+'@www.sendowl.com/api/v1/products'
orderURL = 'https://'+key+':'+secret+'@www.sendowl.com/api/v1_3/orders'

order_id = []
lic_key = []

def Main():
    data = ""
    host = "127.0.0.1"
    port = 5000

    mySocket = socket.socket()
    mySocket.bind((host,port))

    mySocket.listen(5)
    conn, addr = mySocket.accept()
    print ("Connection from: " + str(addr))
    user_key = conn.recv(1024).decode()            

    order_response = requests.get(orderURL, headers=request_type)

    order_root = ET.fromstring(order_response.content)

    for child in order_root.iter('*'):
        if child.tag == 'id':
            order_id.append(child.text)

    i = 0
    while i < len(order_id):
        licenseURL = 'https://'+key+':'+secret+'@www.sendowl.com/api/v1/orders/'+order_id[i]+'/licenses'
        lic_response = requests.get(licenseURL, headers=request_type)
        lic_root = ET.fromstring(lic_response.content)

        for child in lic_root.iter('*'):
            if child.tag == 'key':
                lic_key.append(child.text)
        i += 1

    print("validating...........")
    if data != "SUCCESS":
        if user_key in lic_key:
            message = "Success"
        else:
            message = "Failure"    
        data = str(message).upper()
        print ("sending: " + str(data))
        conn.send(data.encode())

if __name__ == '__main__':
    Main()

0 个答案:

没有答案