模拟买票小程序

将ticket.json当作一个数据库

ticket.json

{"info": "鹰潭 ---> 上海", "count": 2}

服务端.py

# -*- coding: utf-8 -*-
# @Author  : JKey
# Timer    : 2021/1/20 20:39


"""
服务器端
"""
from socket import *
from multiprocessing import Process, Lock
import json
import os

server = socket(AF_INET, SOCK_STREAM)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 8080))  # ip改成你的网络ip,就可以模拟买票了
server.listen(5)


def check():
    with open('ticket.json', 'rt', encoding='utf-8') as f:
        dic = json.load(f)
        return dic


def buy():
    dic = check()
    if dic['count'] > 0:
        dic['count'] -= 1
        with open('ticket.json', mode='wt', encoding='utf-8') as f:
            json.dump(dic, f)
            return '%s购票成功' % os.getpid()
    else:
        return "购票失败"


def accept():
    ...


def signal(conn, client_addr, lock):
    while True:
        try:
            msg = conn.recv(1024)  # 'check', 'buy'
            if len(msg) == 0: break
            msg = msg.decode('utf-8')
            print(msg)
            print(client_addr)
            if msg == 'check':
                res = check()
                res = str(res)
            elif msg == 'buy':
                lock.acquire()
                res = buy()
                lock.release()
            else:
                res = 'no have this func'

            conn.send(res.encode('utf-8'))

        except Exception:
            break


if __name__ == '__main__':
    lock = Lock()
    while True:
        conn, client_addr = server.accept()
        print(f'{client_addr} 连接成功')
        s_signal = Process(target=signal, args=(conn, client_addr, lock))
        s_signal.start()

客户端.py

# -*- coding: utf-8 -*-
# @Author  : JKey  
# Timer    : 2021/1/20 13:19
from socket import *
import os, time, json

# ticket_dic = {"info": "鹰潭 ---> 上海", "count": 5}
# with open(f"ticket.json", 'wt', encoding='utf-8') as f:
#     json.dump(ticket_dic, f)

client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))  # ip改成你的网络ip,就可以模拟买票了

while True:
    r_list = ['check', 'buy']
    print(r_list)
    cmd = input('请输入您的请求>>:').strip()
    if len(cmd) == 0 or len(cmd) > 1024 or cmd not in r_list: continue
    client.send(cmd.encode('utf-8'))
    data = client.recv(1024)
    print(data.decode('utf-8'))

posted on 2021-01-20 21:34  Jkeykey  阅读(204)  评论(0编辑  收藏  举报