利用多線程使socket服務端能夠與多個客戶端同時通信
server
import socketpython
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP多線程
server.bind(('127.0.0.1', 8000)) # 127.0.0.1表明本地dom
server.listen(5) # 半鏈接池socket
print('start...')tcp
while True:
# 通訊循環
conn, client_addr = server.accept()
while True:
try:
# 4. 收到消息receive
data = conn.recv(1024)
print(data)
# 5. 回消息
conn.send(data.upper())
except ConnectionAbortedError:
continue
except ConnectionResetError:
break線程
clientcode
from threading import Thread
import socket, random
count = 0server
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)ip
client.connect(('127.0.0.1',8000))
def task(i):
while True:
msg = input(f'{i}please enter your msg:').strip() # dir
# 3. 發送消息
client.send(msg.encode('utf8'))
# 4. 接收消息
data = client.recv(1024)
print(data)
if name == 'main':
while count <6:
i = random.randint(0,6)
t = Thread(target=task, args=(i,))
t.start()
print(count)
count += 1utf-8