利用多線程使socket服務端能夠與多個客戶端同時通信

利用多線程使socket服務端能夠與多個客戶端同時通信
server
import socketpython

1. 符合TCP協議的手機

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP多線程

2. 綁定手機號 110

server.bind(('127.0.0.1', 8000)) # 127.0.0.1表明本地dom

server.bind(('192.168.11.210',8000)) # 127.0.0.1表明本地

server.listen(5) # 半鏈接池socket

3. 等待客戶端鏈接

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

! /user/bin/ebv python

-- encoding:utf-8 --

from threading import Thread
import socket, random
count = 0server

1. 建立符合TCp協議的手機

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)ip

2. 撥號

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

相關文章
相關標籤/搜索