服务端
from socket import * import pymysql class Database: def __init__(self): self.db = pymysql.connect(host="localhost", port=3306, user="root", password="159357", database="dict", charset="utf8" ) self.cur = self.db.cursor() def close(self): self.db.close() def find_word(self,word1): sql = "select * from dict1 where word=%s;" self.cur.execute(sql,[word1]) data = self.cur.fetchone() if data: print(data) return data[2] else: return "Not Found" def main(): udp_socket = socket(AF_INET,SOCK_DGRAM) server_address = ('192.168.0.143',8888) udp_socket.bind((server_address)) db = Database() while True: try: print('等待接收') data,addr = udp_socket.recvfrom(50) print('接收到:',data.decode()) mean = db.find_word(data.decode()) udp_socket.sendto(mean.encode(),addr) except KeyboardInterrupt: break db.close() udp_socket.close() print("服务结束") if __name__ == '__main__': main()
客户端
from socket import * def main(): udp_socket = socket(AF_INET,SOCK_DGRAM) server_address = ('192.168.0.143',8888) while True: word = input("你要查询的单词:") if not word: break udp_socket.sendto(word.encode(),server_address) data,addr = udp_socket.recvfrom(1024) print("%s:%s"%(word,data.decode())) udp_socket.close() main()