The use of multi-threaded socket server can communicate simultaneously with multiple clients
Server
Import socket
1. Meet the TCP protocol phone
server = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # TCP
2. bound phone number 110
server.bind (( '127.0.0.1', 8000)) # 127.0.0.1 represents the local
server.bind (( '192.168.11.210', 8000)) # 127.0.0.1 represents the local
server.listen (5) # semijoin Pool
3. Wait for the client connections
print('start...')
Links cycle
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
client
! /user/bin/ebv python
-- encoding:utf-8 --
from threading import Thread
import socket, random
count = 0
1. Create a phone line with TCp agreement
client = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
2. Dial
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 += 1