利用多线程使socket服务端可以与多个客户端同时通讯
server
import socket
# 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代表本地
# server.bind(('192.168.11.210',8000)) # 127.0.0.1代表本地
server.listen(5) # 半连接池
# 3. 等待客户端连接
print('start...')
# 链接循环
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. 创建符合TCp协议的手机
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 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 += 1