写一个基于TCP协议套接字,服务端实现接收客户端的连接并发。
#服务端
from threading import Thread
import socket
server = socket.socket()
server.bind(('127.0.0.1',6666))
server.listen(5)
def action(conn):
while True:
rec_data = conn.recv(1024).decode('utf-8')
print(rec_data)
send_data = rec_data.upper()
conn.send(send_data.encode('utf-8'))
while True:
conn,addr = server.accept()#每连接一次才会循环一次,创建一个线程,当没有ip接入时这行代码不执行,所以不会循环下去。
print(addr)
p = Thread(target=action,args=(conn,))
p.start()
#服务端
import socket
client = socket.socket()
client.connect(('127.0.0.1',6666))
while True:
send_data = input('请输入需要发送的消息:').strip()
client.send(send_data.encode('utf-8'))
rec_data = client.recv(1024).decode('utf-8')
print(rec_data)