服务端
#!/usr/bin/env python3
from __future__ import unicode_literals
# coding=utf-8
from socket import *
import os
import pymysql
import time
import sys
import signal
DICT_TEXT = "./dict.txt"
HOST = '0.0.0.0'
PORT = 8000
ADDR = (HOST, PORT)
# 主控制流程
def main():
# 连接数据库
db = pymysql.connect\
('localhost', 'root', '123456', 'dict')
# 创建流式套接字
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
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)
else:
c.close()
def do_child(c, db):
# 循环接收请求
while True:
data = c.recv(128).decode()
print("Request:", data)
if (not data) or data[0] == 'E':
c.close()
sys.exit(0)
elif data[0] == 'R':
do_register(c, db, data)
elif data[0] == "L":
do_login(c, db, data)
elif data[0] == 'Q':
do_query(c, db, data)
elif data[0] == 'H':
do_history(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.se