socket多线程

2020-12-13 14:08

阅读:196

标签:client   def   from   get   ack   name   bin   send   线程   

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()

socket多线程

标签:client   def   from   get   ack   name   bin   send   线程   

原文地址:https://www.cnblogs.com/aden668/p/11552371.html


评论


亲,登录后才可以留言!