码迷,mamicode.com
首页 > 编程语言 > 详细

python小项目电子词典之服务端

时间:2020-05-21 11:50:21      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:back   user   mysq   except   comm   nal   def   cursor   ext   

#涉及知识点tcp,套接字,多进程,mysql,

#注意:mysql部分需要对应自身的库做出修改

from socket import *
import time
import os, sys
import pymysql
import signal

# 创建数据库链接
db = pymysql.connect(‘localhost‘, ‘root‘, ‘root‘, ‘cidian‘)
DICT_TEXT = ‘/home/u/电子词典/dict.txt/‘
HOST = "0.0.0.0"
POST = 8888
ADDR = (HOST, POST)


def do_register(c, db, data):
res = data.split(‘ ‘)
print(res)
name = res[1]
passwd = res[2]
# 创建游标对象
cursor = db.cursor()
sql = ‘select * from user where name="%s"‘ % name
cursor.execute(sql)
# 获取数据库反馈
f = cursor.fetchone()
print(f)

if f != None:
c.send(b‘EXISTS‘)
# 插入用户
sql = ‘insert into user values ("%s","%s")‘ % (name, passwd)
print(sql)
try:
cursor.execute(sql)
db.commit()
c.send(b‘OK‘)
print(‘Ok被调用‘)
except:
db.rollback()
c.send(b‘FALL‘)
print(‘FALL被调用‘)
else:
print(‘%s注册成功‘ % name)


def do_up(c, db, data):
res = data.split(‘ ‘)
cursor = db.cursor()
name = res[1]
passwd = res[2]
sql = ‘select * from user where name="%s" and password="%s"‘ % (name, passwd)
cursor.execute(sql)
f = cursor.fetchone()
if f != None:
c.send(b‘OK‘)
print(‘用户名{}已登录成功‘.format(name))
else:
msg = ‘登录失败,帐号或密码错误‘
c.send(msg.encode())


def do_find(c, db, data):
cursor = db.cursor()
res = data.split(‘ ‘)
word = res[1]
name = res[2]
sql = ‘select * from cidian where english ="%s"‘ % word
cursor.execute(sql)
f = cursor.fetchone()
if f == None:
c.send(b‘nothing for find‘)
else:
print(word)
sql = ‘insert into exl values("%s","%s")‘ % (word, name)
f2 = f[1]
c.send(f2.encode())
cursor.execute(sql)
db.commit()


def qingqiu(c):
while True:
data = c.recv(1024).decode()

if data[0] == ‘Z‘:
do_register(c, db, data)
if data[0] == ‘D‘:
do_up(c, db, data)
if data[0] == ‘Q‘:
sys.exit(‘客户端退出‘)
if data[0] == ‘F‘:
do_find(c, db, data)


def main():
s = socket()
# 设置端口重用
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(ADDR)

# 设置监听
s.listen(5)
# 忽略子进程信号
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
print(‘{}is waiting for connect‘.format(POST))
while True:
try:

c, addr = s.accept()
print(‘connect from‘, addr)
except:
s.close()
sys.exit()
pid = os.fork()
if pid == 0:
s.close()
print(‘子进程准备处理请求‘)
qingqiu(c)

else:
c.close()
continue


if __name__ == ‘__main__‘:
main()

python小项目电子词典之服务端

标签:back   user   mysq   except   comm   nal   def   cursor   ext   

原文地址:https://www.cnblogs.com/qinminmin/p/12929652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!