利用socketserver实现异步多线程服务端简单聊天功能

废话不多说,直接上代码

程序组成

数据访问层:model-------chat_log.py(用于保存聊天记录及展示)

           ---user_info.py(用户登录信息表,验证通过才能聊天)

公共功能层:utility-------sqlhelper.py(用于处理查询及插入数据的操作)

           ---conf.py(用于保存数据库连接字符串)

主程序:server.py--------Socket服务端

   client.py----------Socket客户端

 

server.py

 1 #!/usr/bin/env python
 2 #_*_ coding:utf-8 _*_
 3 import SocketServer
 4 import json
 5 import time
 6 from model.userinfo import UserInfo
 7 from model.chat_log import ChatLog
 8 
 9 class  MyServer(SocketServer.BaseRequestHandler):
10     
11     def setup(self):
12         pass
13 
14     def handle(self):       
15         container = {'key':'','data':''}
16         container['data'] = 'ok...'
17         conn = self.request
18         conn.sendall(json.dumps(container))
19         
20         Flag =True
21         while Flag:
22             try:
23                 datetime = time.strftime('%Y-%m-%d %H:%M:%S')
24                 data = conn.recv(1024)
25                 print data
26                 recv_data = json.loads(data)
27                 if recv_data['data'] == 'exit':
28                     conn.close()
29                     break
30                 #key为空,表示用户没有登录或登录失败
31                 if not recv_data['key']:
32                     name,pwd = recv_data['data']
33                     re = UserInfo().ChechkLogin(name, pwd)
34                     #re = 1
35                     if re:
36                         recv_data['key'] = re
37                         recv_data['data'] = '约吗'
38                     else:
39                         recv_data['data'] = 'failed'
40                     conn.sendall(json.dumps(recv_data))
41                 #用户已经登陆
42                 else:                    
43                     if recv_data['data'] == 'list':
44                         ChatLog().ShowLog()
45                     elif recv_data['data'].__contains__('yes'):
46                         ChatLog().SaveLog(recv_data['data'], datetime)
47                         recv_data['data'] = 'i am gay!'
48                         ChatLog().SaveLog(recv_data['data'], datetime)                     
49                     else:
50                         ChatLog().SaveLog(recv_data['data'], datetime)
51                         recv_data['data'] = 'what?'
52                         ChatLog().SaveLog(recv_data['data'], datetime)
53                     conn.sendall(json.dumps(recv_data))
54             except Exception,e:
55                 print e
56                 Flag = False
57                        
58     def finish(self):
59         pass
60         
61 if __name__ == '__main__':
62     server = SocketServer.ThreadingTCPServer(('127.0.0.1',9999),MyServer)
63     server.serve_forever()
View Code

client.py

 1 #!/usr/bin/env python
 2 #_*_ coding:utf-8 _*_
 3 import socket
 4 import json
 5 
 6 #创建客户端socket对象
 7 client = socket.socket()
 8 ip_port = ('127.0.0.1',9999)
 9 #客户端连接服务端
10 client.connect(ip_port)
11 #客户端接收数据
12 while True:
13     data = client.recv(1024)
14     #print data
15     client_recv_data = json.loads(data)
16     print client_recv_data['data']
17     if not client_recv_data['key']:
18         name = raw_input('username:')
19         pwd = raw_input('pasword:')
20         client_recv_data['data'] = (name,pwd)
21         client.send(json.dumps(client_recv_data))
22     else:       
23         inp = raw_input('client:')
24         client_recv_data['data'] = inp
25         client.send(json.dumps(client_recv_data))
26         if inp == 'exit':
27             break
View Code

sqlhelper.py

 1 #!/usr/bin/env python
 2 #_*_ coding:utf-8 _*_
 3 import MySQLdb
 4 import conf
 5 
 6 class MysqlHelper(object):
 7     def __init__(self):
 8         self.__conn_dict = conf.conn_dict
 9         
10     def GetDict(self,sql,params):
11         conn = MySQLdb.connect(**self.__conn_dict)
12         cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
13         
14         #cur = conn.cursor()
15         reCount = cur.execute(sql,params)
16         nRet = cur.fetchall()
17         
18         cur.close()
19         conn.close()
20         return nRet
21     def GetOne(self,sql,params):
22         conn = MySQLdb.connect(**self.__conn_dict)
23         cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
24         
25         #cur = conn.cursor()
26         reCount = cur.execute(sql,params)
27         nRet = cur.fetchone()
28         
29         cur.close()
30         conn.close()
31         return nRet
32     
33     def InsertOne(self,sql,params):
34         conn = MySQLdb.connect(**self.__conn_dict)
35         cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
36         
37         reCount = cur.execute(sql,params)
38         conn.commit()
39         
40         cur.close()
41         conn.close()
View Code

conf.py

1 #!/usr/bin/env python
2 #_*_ coding:utf-8 _*_
3 conn_dict = dict(host='127.0.0.1',user='root',passwd='123456',db='08day05')

chat_log.py

 1 #!/usr/bin/env python
 2 #_*_ coding:utf-8 _*_
 3 from utility.sqlhelper import MysqlHelper
 4 class ChatLog():
 5     def __init__(self):
 6         self.__helper = MysqlHelper()
 7     def SaveLog(self,msg,insert_day):
 8         sql = 'insert into chat_log(msg,time) values(%s,%s)'
 9         params = (msg,insert_day)
10         self.__helper.InsertOne(sql, params)
11     def ShowLog(self):
12         sql = 'select * from chat_log'
13         params = ()
14         result = str(self.__helper.GetDict(sql,params))
15         return result
16         #print result
17         '''
18         for msg_dict in result:
19             for item in msg_dict:
20                 print item+':'+str(msg_dict[item])
21         '''        
22 
23 #log1 = ChatLog()
24 #log1.ShowLog()

userinfo.py

 1 #!/usr/bin/env python
 2 #_*_ coding:utf-8 _*_
 3 from utility.sqlhelper import MysqlHelper
 4 
 5 class UserInfo(object):
 6     def __init__(self):
 7         self.__helper = MysqlHelper()
 8     
 9     def ChechkLogin(self,username,password):
10         sql = 'select id from userinfo where name = %s and password = %s'
11         params = (username,password)
12         result = self.__helper.GetOne(sql, params)
13         if result:
14             return result
15         else:
16             return False
17         

 

转载于:https://www.cnblogs.com/songbq/p/5070612.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值