Python socket TCP 多客户端 多线程通信
发布日期:2021-05-06 22:01:55 浏览次数:27 分类:精选文章

本文共 3361 字,大约阅读时间需要 11 分钟。

写完才想起来,公司用的UDP,这段代码没啥用了,呵呵!

#!/usr/bin/python3# 导入 socket、sys 模块import sysimport timeimport structimport randomimport socketimport codecs  # 解析发送报文import tracebackimport threadingframeid = 0threadargs = []errlst = []def recvcmd(sock, threadid):    try:        global threadargs        while True:            buf = sock.recv(2048)            if buf == b'':                print('client:', sock, 'disconnected!')                threadargs[threadid]['inuse'] = 0                break            else:                print('buf:', buf)                sock.send(buf)    except:        traceback.print_exc()        print('recv error!')        # 关闭与客户端的连接        sock.close()def udplist(sock, errlvl, errtype, errmodule, errcode):    lst = [0xFF, 0x5A, 0xA5]    length = 0    lst.append(length)    lst.append(length)    lst.append(0)    lst.append(0xE1)    global frameid    frameid = frameid + 1    lst.append(frameid >> 8)    lst.append(frameid & 0xFF)    lst.append((errlvl << 4) + errtype)    lst.append(errmodule)    lst.append(errcode >> 8)    lst.append(errcode & 0xFF)    check = 0    lst.append(check)    length = len(lst[3:])    lst[3] = length >> 8    lst[4] = length & 0xFF    sum = 0    for cell in lst[3:-1]:        sum = sum ^ cell    lst[-1] = sum    for i in range(len(lst)):        print(hex(lst[i]) + ' ', end='')        a = struct.pack('>B', lst[i])        sock.send(a)    print('\n')def sendlist(sock, threadid):    try:        e = threading.Event()        while not e.wait(1):            if len(errlst) > 0:                for x in errlst:                    udplist(sock, x['errlvl'], x['errtype'], x['errmodule'], x['errcode'])    except ConnectionAbortedError:        print('send failed!')        threadargs[threadid]['inuse'] = 0        # 关闭与客户端的连接        sock.close()def generate_err():    global errlst    e = threading.Event()    while not e.wait(10):        errlvl = random.randint(0, 5)        errtype = random.randint(1, 8)        errmodule = random.randint(1, 65)        errcode = random.randint(1, 60)        temp = {   'errlvl': errlvl, 'errtype': errtype, 'errmodule': errmodule, 'errcode': errcode}        errlst.append(temp)if __name__ == '__main__':    t = threading.Thread(target=generate_err).start()    # 创建 socket 对象    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    # 获取本地主机名    host = socket.gethostname()    port = 9999    # 绑定端口号    serversocket.bind((host, port))    # 设置最大连接数,超过后排队    serversocket.listen(10)    threadid = 0    threadargs = [{   } for x in range(10)]    for i in range(10):        threadargs[i].update({   'inuse': 0, 'threadsend': '', 'threadrecv': ''})    while True:        # 建立客户端连接        clientsocket, addr = serversocket.accept()        print("连接地址: %s" % str(addr))        while threadargs[threadid]['inuse'] == 1:            # 超过10路同时连接会陷入死循环,但不影响仍在运行的线程            if threadid < 9:                threadid = threadid + 1            else:                threadid = 0        threadargs[threadid]['inuse'] = 1        threadargs[threadid]['threadsend'] = threading.Thread(target=sendlist, args=(clientsocket, threadid))        threadargs[threadid]['threadsend'].start()        threadargs[threadid]['threadrecv'] = threading.Thread(target=recvcmd, args=(clientsocket, threadid))        threadargs[threadid]['threadrecv'].start()    clientsocket.close()    serversocket.close()
上一篇:PYTHON UDP只能接收本地报文,无法接收其他主机通过路由器发过来的报文
下一篇:Django文件上传

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年03月27日 02时28分01秒