使用UDP完成网络单词查询,利用dict数据库

【注】UDP的优缺点:

        1:传输效率高

        2:易出现数据丢失

        3:以数据报的形式传输

思路:

        step1:获取客户端请求

        step2:查询单词

        step3:响应客户端

Client.py

from socket import *

SERVICE_ADDR = ("127.0.0.1", 8888)

udp_socket = socket(AF_INET, SOCK_DGRAM)
while True:
    word = input(">>")
    if word == "##":
        break
    udp_socket.sendto(word.encode(), SERVICE_ADDR)
    data, addr = udp_socket.recvfrom(1024)
    print(f"{data.decode()}")
udp_socket.close()

Server.py

import pymysql
from socket import *


class Query:
    # 连接数据库
    def __init__(self):
        # 连接数据库
        self.count = 0
        self.kwargs = {
            "host": "localhost",
            "port": 3306,
            "user": "root",
            "password": "123456",
            "database": "dict",
            "charset": "utf8"
        }
        self.db = pymysql.connect(**self.kwargs)
        self.cur = self.db.cursor()
        # udp套接字对象
        self.udp_socket = socket(AF_INET, SOCK_DGRAM)
        self.udp_socket.bind(("0.0.0.0", 8888))

    def select_db(self, query_word):
        query_sql = "select mean from words where word = %s"
        self.cur.execute(query_sql, [query_word])
        mean = self.cur.fetchone()  # 返回的是元组
        if mean == None:  # 查不到
            return
        return mean[0]

    def run(self):
        while True:
            data, addr = self.udp_socket.recvfrom(1024)  # 获取请求
            self.count += 1
            print(f"请求{self.count},查询单词:{data.decode()},用户ip:{addr[0]}")
            mean = self.select_db(data.decode())
            if mean == None:
                self.udp_socket.sendto("无结果!".encode(), addr)
            else:
                self.udp_socket.sendto(mean.encode(), addr)


if __name__ == '__main__':
    query = Query()
    query.run()

上一篇:ChatGPT深度科研应用、数据分析及机器学习、AI绘图与高效论文撰写教程