python判断MYSQL连接正常socket通讯一
1.写一个判断连接MYSQL正确与否的类:
import MySQLdb
class connDB:
dbhost = '192.168.#.#'
dbport = '3306'
database = 'db'
dbuser = 'root'
dbpasswd = '320'
def __init__(self):
pass
def connect(self):
status=0
try:
conn= MySQLdb.connect(self.dbhost,self.dbuser,self.dbpasswd,self.database)
except Exception,e:
status=1
return status
def __del__(self):
pass
if __name__ == '__main__':
ob=connDB()
print ob.connect()
2.布署服务器端的代码抓取回来MYSQL的状态信息
if __name__ == '__main__':
import socket,time
from connDB import connDB
def getStatus():
ob=connDB()
rs=ob.connect()
return rs
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost',8005))
sock.listen(10)
connection,address = sock.accept()
connection.settimeout(5)
while True:
try:
time.sleep(5)
#connection.send('1')
connection.send(str(getStatus()))
except socket.timeout:
print 'time out'
break
每隔5S去抓取一次然后返回到客户端!
3.客户端的代码如下:
if __name__ == '__main__':
import socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(('localhost',8005))
while True:
try:
print sock.recv(1024)
except Exception,e:
print 'error'