-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdict_server.py
More file actions
112 lines (97 loc) · 2.28 KB
/
Copy pathdict_server.py
File metadata and controls
112 lines (97 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
'''
dict project for AID
'''
from socket import *
import pymysql
import os,sys
import time
import signal
#定义全局变量
if len(sys.argv) < 3:
print('''Start as:
python3 dict_server.py 0.0.0.0 8000
''')
sys.exit(0)
HOST = sys.argv[1]
PORT = int(sys.argv[2])
ADDR = (HOST,PORT)
DICT_TEXT = "./dict.txt"
#搭建网络链接
def main():
#连接数据库
db = pymysql.connect('localhost','root',\
'123456','dict')
#创建套接字
s = socket()
s.bind(ADDR)
s.listen(5)
#僵尸进程处理
signal.signal(signal.SIGCHLD,signal.SIG_IGN)
while True:
try:
c,addr = s.accept()
print("Connect from",addr)
except KeyboardInterrupt:
s.close()
sys.exit("服务器退出")
except Exception as e:
print(e)
continue
#创建子进程
pid = os.fork()
if pid == 0:
s.close()
do_child(c,db)
sys.exit()
else:
c.close()
#处理客户端请求
def do_child(c,db):
while True:
#接收客户端请求
data = c.recv(1024).decode()
print(c.getpeername(),':',data)
if not data or data[0] == 'E':
c.close()
sys.exit()
elif data[0] == 'R':
do_register(c,db,data)
elif data[0] == 'L':
do_login(c,db,data)
def do_register(c,db,data):
l = data.split(' ')
name = l[1]
passwd = l[2]
cursor = db.cursor()
sql = "select * from user where name='%s'"%name
cursor.execute(sql)
r = cursor.fetchone()
if r != None:
c.send(b'EXISTS')
return
#插入用户
sql = "insert into user (name,passwd) values \
('%s','%s')"%(name,passwd)
try:
cursor.execute(sql)
db.commit()
c.send(b'OK')
except:
db.rollback()
c.send(b'FAIL')
def do_login(c,db,data):
l = data.split(' ')
name = l[1]
passwd = l[2]
cursor = db.cursor()
sql = "select * from user where name='%s' and \
passwd='%s'"%(name,passwd)
#查询用户
cursor.execute(sql)
r = cursor.fetchone()
if r == None:
c.send(b'FAIL')
else:
c.send(b'OK')
if __name__ == "__main__":
main()