Python-在其中执行MySQLdb命令并通过套接字连接将其发送给客户端

时间:2019-01-26 03:36:14

标签: python mysql sockets mysql-python python-sockets

我一直在尝试使用python MySQLdbsocket模块通过套接字模块发送MySQL命令。从客户端发送的命令在服务器上执行,但是仅在杀死客户端代码之后。如何更改代码,以便服务器执行并将命令发送给客户端?

我尝试关闭连接,但这没用。

服务器:

import socket
import MySQLdb
import time

class Server():
    def __init__(self, host, port, listen):
        self.host = host
        self.port = port
        self.listen = listen

    def connect(self, dbconfig):
        self.cnx = socket.socket()
        self.cnx.bind((self.host, self.port))

        self.cnx.listen(self.listen)
        self.c, self.addr = self.cnx.accept()

        self.conn = MySQLdb.connect(**dbconfig)
        self.cursor = self.conn.cursor()

    def send(self, msg):
        self.msg = msg
        self.c.send(self.msg)

    def receiveEx(self, int):
        self.int = int
        recv = self.c.recv(self.int)

        if recv == "" or recv == " ":
            pass
        else:
            self.cursor.execute(recv)
            self.conn.commit()
            results = self.cursor.fetchall()

            self.throw = self.c.recv(self.int) + "   <:>   " + str(results)
            return self.throw


    def kill(self):
        self.c.close()
        self.cursor.close()
        self.conn.close()


#TEST

dbconfig = {'host' : '127.0.0.1',
            'user': 'root',
            'password' : 'toor',
            'database' : 'MYtestDB'}


serv = Server("192.168.1.6", 80, 5)
serv.connect(dbconfig)

msg = serv.receiveEx(1024)
print(msg)
serv.send(msg)

time.sleep(20)

serv.kill()

客户

import socket


class Client():
    def __init__(self, host, port, listen):
        self.host = host
        self.port = port
        self.listen = listen


    def connect(self):
        self.cnx = socket.socket()
        self.cnx.connect((self.host, self.port))


    def send(self, msg):
        self.msg = msg
        self.cnx.send(self.msg)

    def receive(self, int):
        self.int = int
        self.get = self.cnx.recv(self.int)
        return self.get

    def kill(self):
        self.cnx.close()


#TEST
cli = Client("192.168.1.6", 80, 5)
cli.connect()

while True:
    inp = raw_input("SQL> ")
    cli.send(inp)
    msg = cli.receive(1024)
    print(msg)

cli.kill()

希望社区可以提供帮助。预先感谢

0 个答案:

没有答案