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