心痕610
2021-10-20 09:45
采纳率: 100%
浏览 35
已结题

python服务器一个端口如何传输三组数据

我需要传输的数据有三组,而且没有什么顺序可言。数据格式如下面。我创建了三个不同的线程。我只能运行第一个线程yangan(),ruku()和jieshu()它会报套接字的错误。求大家指教指教

img

 
# 打开数据库连接                127.0.0.1
conn = pymysql.connect(host="localhost", port=3306, user="root", password="123", database="tushuguan",
                    charset="utf8")
zhizhen = conn.cursor()
def reconnect():
    # TODO: add auto reconnect
    try:
        db = pymysql.connect(host="localhost", port=3306, user="root", password="123", database="tushuguan",
                             charset="utf8")
        return db
    except pymysql.Error as e:
        print("Mysql Error: %s" % (e,))
        return False
app = Flask(__name__)
CORS(app, resource=r'/*')  # 解决跨域问题
isChange = False
shuju= False
event = threading.Event
# 1.创建套接字 socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置为非阻塞模式
server.setblocking(0)
# 端口复用
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 2.绑定 bind
server.bind(('192.168.1.109', 8235))
# 3.监听 listen'
server.listen(5)
print('starting...')
def yangan():
    rlist = [server]
    # 初始化写入数据的监听列表,最开始并没有客户端连接进来,所以列表为空
    wlist = []
    xlist = []
    while True:
        # 监控IO发生
        # select函数语法: rs,ws,xs=select(rlist, wlist, xlist[], timeout])
        # 提交监测我们关注的IO,阻塞等待IO发生
        rs, ws, xs = select(rlist, wlist, xlist)
        for r in rs:  # 遍历读列表(收到客户端请求的对象)
            if r is server:  # 分情况讨论,如果是监听套接字,说明由客户端连接服务端,做以下事情(只能读)
                # 接收连接
                c, client_addr = r.accept()  # #如果是server套接字对象接收到请求,则说明是新的用户连接
                print(client_addr)
                c.setblocking(0)
                rlist.append(c)  # 将新生成的套接字添加到读监听列表list中,让操作系统去监控
                wlist.append(c)
                time.sleep(1)
                header_dic = {'status': 'ok'}
                header_json = json.dumps(header_dic)  # json格式的字符串
                header_bytes = header_json.encode('utf-8')  # 将报头格式转换为bytes
                c.send(header_bytes)
                time.sleep(1)
                c.send(header_bytes)
                print(header_bytes)
                print("连接响应成功")
            else:  # 如果不是server套接字对象接收的请求,则说明是已有的现成连接,以便保持持续的连接
                cmd = r.recv(1024).decode('utf-8')  # 接收客户端传过来的数据
                if not cmd:  # 如果没有发送过来任何数据
                    rlist.remove(r)  # 将当前套接字移除出rlist列表,使select不再监管此对象
                    r.close()  # 将当前套接字关闭
                else:
                    data_res = cmd
                    print(data_res)
                    result = json.loads(data_res)
                    print(result)
                    print(type(result))
                    yangano = result.get('yangano')
                    yangant = result.get('yangant')
                    ygzhuangtai = result.get('ygzhuangtai')
                    ffzhuangtai = result.get('ffzhuangtai')
                    print(temp, hum, lux, aq)
                    zhizhen.execute("insert into yangan (yangano,yangant,ygzhuangtai,ffzhuangtai) values (\"" + str(yangano) +
                     "\",\"" + str(yangant) + "\",\"" + str(ygzhuangtai) + "\",\"" + str(ffzhuangtai) + "\")")
                    conn.commit()  # 提交,使操作生效
                    print("add  successfully!")
                    print("接收到数据")
                    data_dic = {'status': 'okk'}
                    data_json = json.dumps(data_dic)  # json格式的字符串
                    data_bytes = data_json.encode('utf-8')  # 将报头格式转换为bytes
                    r.send(data_bytes)
                    print(data_bytes)
                    print(type(data_bytes))
                    print("发送数据响应成功")
def ruku():
    while True:
        rlist = [server]
        # 初始化写入数据的监听列表,最开始并没有客户端连接进来,所以列表为空
        wlist = []
        xlist = []
        rs, ws, xs = select(rlist, wlist, xlist)
        cmd = recv(1024).decode('utf-8')  # 接收客户端传过来的数据
        if not cmd:  # 如果没有发送过来任何数据
            close()  # 将当前套接字关闭
        else:
            data_res = cmd
            print(data_res)
            result = json.loads(data_res)
            print(result)
            print(type(result))
            id = result.get('id')
            shuming= result.get('shuming')
            weizhi= result.get('weizhi')
            print(id, shuming, weizhi)
            zhizhen.execute("insert into data(id,shuming,weizhi) values (\"" + str(id) + "\",\"" + str(shuming) + "\",\"" + str(weizhi) + "\")")
            conn.commit()  # 提交,使操作生效
            print("add  successfully!")
            print("接收到数据")
            data_dic = {'status': 'okk'}
            data_json = json.dumps(data_dic)  # json格式的字符串
            data_bytes = data_json.encode('utf-8')  # 将报头格式转换为bytes
            r.send(data_bytes)
            print(data_bytes)
            print(type(data_bytes))
            print("发送数据响应成功")
def jieshu():
    while True:
        rlist = [server]
        # 初始化写入数据的监听列表,最开始并没有客户端连接进来,所以列表为空
        wlist = []
        xlist = []
        rs, ws, xs = select(rlist, wlist, xlist)
        cmd = r.recv(1024).decode('utf-8')  # 接收客户端传过来的数据
        if not cmd:  # 如果没有发送过来任何数据
            r.close()  # 将当前套接字关闭
        else:
            data_res = cmd
            print(data_res)
            result = json.loads(data_res)
            print(result)
            print(type(result))
            id =result.get('id')
            name = result.get('name')
            zhuangtai = result.get('zhuangtai')
            print(id, name,zhuangtai)
            zhizhen.execute("update data set( name,zhuangtai) values (\"" + str(name) + "\",\"" + str(zhuangtai) + "\" where id=\"" + str(id) + "\")")
            conn.commit()  # 提交,使操作生效
            print("update  successfully!")
            data_dic = {'status': 'okk'}
            data_json = json.dumps(data_dic)  # json格式的字符串
            data_bytes = data_json.encode('utf-8')  # 将报头格式转换为bytes
            r.send(data_bytes)
            print(data_bytes)
            print(type(data_bytes))
            print("发送数据响应成功")
 

  • 好问题 提建议
  • 收藏

1条回答 默认 最新

  • zlebhs 2021-10-20 10:02
    已采纳

    我不知道你为什么要创建3条线程来跑,简单浏览了一下(主要代码太乱了,懒得看了),难道不应该是来一个客户端,创建一条线程为其服务?

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题