运维开发网

socket多线程

运维开发网 https://www.qedev.com 2020-07-21 13:34 出处:网络 作者:运维开发网整理
socket多线程 客户端 import socket from threading import Thread,currentThread def client_demo(): client=socket.socket() client.connect(('127.0.0.1',8081)) while True: msg=f'{currentThrea

socket多线程

客户端

import socket
from threading import Thread,currentThread

def client_demo():
    client=socket.socket()
    client.connect(('127.0.0.1',8081))
    while True:
        msg=f'{currentThread().name}'
        if len(msg)==0: continue
        client.send(msg.encode('utf8'))
        feedback=client.recv(1024)
        print(feedback.decode('utf8'))

    client.close()
    
if __name__ == '__main__':
    for i in range(20):
        t=Thread(target=client_demo)
        t.start()

服务端

import socket
from threading import Thread

def talk(conn):
    while True:
        try:
            msg=conn.recv(1024)
            if len(msg)==0 :break
            conn.send(msg.upper())
        except ConnectionResetError:
            print('客户端关闭了一个链接')
            break
    conn.close()

def sever_demo():
    server=socket.socket()
    server.bind(('127.0.0.1',8081))
    server.listen(5)
    
    while True:
        conn,addr=server.accept()
        t=Thread(target=talk,args=(conn,))
        t.start()
if __name__ == '__main__':
    sever_demo()
0

精彩评论

暂无评论...
验证码 换一张
取 消