标签:
socket两端建立连接,不断开的连接的情况下做数据交互,客户端发送数据和服务端返回数据。直到客户端要求断开,则关闭连接。
代码目录结构:
__init__.py :空
models.py:
#!/usr/bin/env python #coding:utf-8 from sqlhelper import MySqlHelper class UserInfo: def __init__(self): self.sqlHelper = MySqlHelper() def CheckLogin(self,name,pwd): ‘‘‘验证用户名是否合法 @param name:用户名 @param pwd:密码 @return: 如果登录成功,返回该用户的自增ID;否则,返回False ‘‘‘ sql = ‘‘‘select Nid,Name,Password from UserInfo where Name=%s and Password = %s‘‘‘ params = (name,pwd,) result = self.sqlHelper.GetSimple(sql, params) if not result: return False else: return result[‘Nid‘] class ChatRecord: def __init__(self): self.sqlHelper = MySqlHelper() def InsertRecord(self,message,date,userid): ‘‘‘插入聊天记录 @param message:聊天信息 @param date:时间 @param userid:用户ID @return: 如果聊天记录插入成功,返回True;否则返回False ‘‘‘ sql = ‘‘‘insert into ChatRecord(Message,Date,UserId) values(%s,%s,%s)‘‘‘ params = (message,date,userid,) result = self.sqlHelper.InsSample(sql, params) #插入聊天记录,返回受影响条数,如果受影响条数为 1,表示插入成功 if result != 1: return False else: return True def GetRecord(self,userid): ‘‘‘获取聊天记录 @param userid:用户ID @return: 所有聊天记录 ‘‘‘ sql = ‘‘‘ select Message,Date from ChatRecord where UserId=%s ‘‘‘ params = (userid,) result = self.sqlHelper.GetDict(sql, params)#根据用户ID,获取该用户的所有聊天记录 print result if not result: return False else: return result
sqlhelper.py:
#!/usr/bin/env python #coding:utf-8 import MySQLdb import _mysql_exceptions class MySqlHelper: def __init__(self): self.__connDict = {‘host‘:‘127.0.0.1‘,‘user‘:‘root‘,‘passwd‘:‘1234‘,‘db‘:‘milkteaDB‘} def GetSimple(self,sql,params): ‘‘‘获取单条数据 @param sql:sql语句 @param params:参数 @return: 数据 ‘‘‘ conn = MySQLdb.connect(**self.__connDict) cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) cur.execute(sql,params) data = cur.fetchone() cur.close() conn.close() return data def GetDict(self,sql,params): ‘‘‘获取多条数据(字典类型)‘‘‘ conn = MySQLdb.connect(**self.__connDict) cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) cur.execute(sql,params) data = cur.fetchall() cur.close() conn.close() return data def InsSample(self,sql,params): ‘‘‘插入单条数据 @return: 受影响的条数 ‘‘‘ conn = MySQLdb.connect(**self.__connDict) cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) count = cur.execute(sql,params) conn.commit() cur.close() conn.close() return count def InsSample_ReturnId(self,sql,params): ‘‘‘插入单条数据 @return: 返回自增ID ‘‘‘ conn = MySQLdb.connect(**self.__connDict) cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) cur.execute(sql,params) id = cur.lastrowid conn.commit() cur.close() conn.close() return id
client.py
#!/usr/bin/env python #coding:GBK import socket import sys import json ip_port = (‘127.0.0.1‘,9998) sk = socket.socket() sk.connect(ip_port) container = {‘key‘:‘‘,‘data‘:‘‘} while True: data = sk.recv(1024) rev_data = json.loads(data) print rev_data[‘data‘] if not rev_data[‘key‘]: user = raw_input(‘username:‘) pwd = raw_input(‘password:‘) rev_data[‘data‘]=[user,pwd] sk.sendall(json.dumps(rev_data)) else: inp = raw_input(‘reply:‘) rev_data[‘data‘] = inp sk.sendall(json.dumps(rev_data)) if inp == ‘exit‘: break sk.close()
server.py:
#!/usr/bin/env python #coding:utf-8 import SocketServer import json import time from backend.models import UserInfo,ChatRecord class MyServer(SocketServer.BaseRequestHandler): def setup(self): pass def handle(self): #userinfo = UserInfo() #实例化一个用户表操作类 #chatrecord = ChatRecord() #实例化一个记录表操作类 container = {‘key‘:‘‘,‘data‘:‘‘} container[‘data‘] = ‘ok...‘ conn = self.request conn.sendall(json.dumps(container)) Flag = True while Flag: try: data = conn.recv(1024) print data rev_data = json.loads(data) if rev_data[‘data‘] == ‘exit‘: conn.close() break #如果key为空,则表示用户没有登录或登录失败 if not rev_data[‘key‘]: name,pwd = rev_data[‘data‘] #re = userinfo.CheckLogin(name, pwd) re = 1 if re: rev_data[‘key‘] = re rev_data[‘data‘] = ‘约吗?‘ else: rev_data[‘data‘] = ‘failed.‘ conn.sendall(json.dumps(rev_data)) #用户已经登录 else: datetime = time.strftime(‘%Y-%m-%d %H:%M:%S‘) if rev_data[‘data‘]==‘list‘: #聊天记录 #rev_data[‘data‘] = chatrecord.GetRecord(rev_data[‘key‘]) pass elif rev_data[‘data‘].__contains__(‘yes‘): #如果用户输入的是yes,那么就把用户输入的记录保存到数据 #chatrecord.InsertRecord(rev_data[‘data‘], datetime, rev_data[‘key‘]) rev_data[‘data‘] = ‘I am gay.‘ #把聊天机器人的回复也保存到数据库 #chatrecord.InsertRecord(rev_data[‘data‘], datetime, rev_data[‘key‘]) else: #如果用户输入的不是yes,把用户输入的记录保存到数据 #chatrecord.InsertRecord(rev_data[‘data‘], datetime, rev_data[‘key‘]) rev_data[‘data‘] = ‘what?‘ #把聊天机器人的回复也保存到数据库 #chatrecord.InsertRecord(rev_data[‘data‘], datetime, rev_data[‘key‘]) conn.sendall(json.dumps(rev_data)) except Exception,e: print e Flag = False def finish(self): pass if __name__ == ‘__main__‘: server = SocketServer.ThreadingTCPServer((‘127.0.0.1‘,9998),MyServer) server.serve_forever()
标签:
原文地址:http://www.cnblogs.com/robinunix/p/5164495.html