Python:从数据库

时间:2015-10-30 20:30:20

标签: python tcp

我有一个从客户端接收tcp数据的python脚本,我想向特定客户端发送响应(我处理的数量超过500)。这个命令来自一个mysql数据库,我通过字典处理clientsocket,但是当它收到很多连接时,脚本就会关闭。

如何将clientocket存储在mysql数据库中,或者哪个是处理clientocket的最佳方式?

我的代码是:

import thread
from socket import *

def sendCommand():
    try:
        for clientsocket,id_client in conn_dict.iteritems():
            if id_cliente == "TEST_from_mysql_db":
                clientsocket.send("ACK SEND")
                break
    except:
        print "NO"

def handler(clientsocket, clientaddr):
    print "Accepted connection from: ", clientaddr
    while 1:
        data = clientsocket.recv(buf)
        if not data:
            break
        else:
            conn_dict[clientsocket] = id_client
            sendCommand()
    clientsocket.close()

if __name__ == "__main__":

    conn_dict = dict()
    host = str("XXX.XXX.XXX.XXX")
    port = XXX
    buf = 1024

    addr = (host, port)
    serversocket = socket(AF_INET, SOCK_STREAM)
    serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversocket.bind(addr)
    serversocket.listen(2)

    while 1:
        print "Server is listening for connections\n"
        clientsocket, clientaddr = serversocket.accept()
        thread.start_new_thread(handler, (clientsocket, clientaddr))
    serversocket.close()

0 个答案:

没有答案