import socket import json s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) host='' port=1234 s.bind((host,port)) s.listen(3) while True: client,ipaddr=s.accept() print "Got a connect from %s" %str(ipaddr) data=client.recv(1024) metadata=json.loads(data) print "receive data:%s" %metadata[1]['name'] client.send("echo:"+data) client.close()客户端:
#! /usr/bin/env python import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) host='localhost' port=1234 s.connect((host,port)) #fileHandle = open('/root/test') s.send('fileHandle') data=s.recv(1024) print "Reply from server----%s" %data只要把客户端对应读取的文件 用json可是存数据 服务器端收到客户端发过来的数据
Python通过MySQL-Python把数据写进MySQL数据库
下载和安装
wget http://jaist.dl.sourceforge.net/project/mysql-python/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz tar fvxz MySQL-python-1.2.3.tar.gz -C /usr/src/MySQL-python-1.2.3/ python setup.py build python setup.py install
连接数据的代码:
,%s,%s,%s,%s¥
import MySQLdb conn=MySQLdb.connect(host="localhost",user="root",passwd="123456",db="python",unix_socket="/tmp/mysql.sock") cursor=conn.cursor() sql = "insert into python values(%s,%s)" param = (ip,status) cursor.execute(sql,param) conn.commit() cursor.close() conn.close()
把链接数据库的代码整合进服务器端的代码:
和服务器端写到一起 #!/usr/bin/env python import socket import json import MySQLdb s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) host='' port=1234 s.bind((host,port)) s.listen(3) while True: client,ipaddr=s.accept() print "Got a connect from %s" %str(ipaddr) data=client.recv(1024) metadata=json.loads(data) ip = metadata[0]['ip'] status = metadata[1]['status'] conn = MySQLdb.connect(host="localhost",user="root",passwd="123456",db="python",unix_socket="/tmp/mysql.sock") cursor=conn.cursor() sql = "insert into python values(%s,%s)" param = (ip,status) cursor.execute(sql,param) conn.commit() cursor.close() conn.close() #print "receive data:%s" %metadata client.send("echo:"+data) client.close()
再添加一个故障处理,来处理从客户端接受的json格式数据key不符的问题,添加完的代码如下:
#!/usr/bin/env python import socket import json import MySQLdb s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) host = '' port = 1234 s.bind((host,port)) s.listen(3) while True: client,ipaddr = s.accept() print "Got a connect from %s" %str(ipaddr) data=client.recv(1024) metadata=json.loads(data) try: ip = metadata[0]['ip'] status = metadata[1]['status'] conn = MySQLdb.connect(host="localhost",user="root",passwd="123456",db="python",unix_socket="/tmp/mysql.sock") cursor=conn.cursor() sql = "insert into python values(%s,%s)" param = (ip,status) cursor.execute(sql,param) conn.commit() cursor.close() conn.close() client.send("echo:"+data) client.close() except: client.send("Data ERROR") client.close()