socket多线程
Posted aden668
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket多线程相关的知识,希望对你有一定的参考价值。
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多线程的主要内容,如果未能解决你的问题,请参考以下文章
Python中socket经ssl加密后server开多线程
Python3 socket 实现即时通讯脚本,threading 多线程