'''
写一个基于TCP协议套接字,服务端实现接收客户端的连接并发
'''
client
import socket
import time
client = socket.socket()
client.connect(
('127.0.0.1', 9527)
)
print('启动客户端...')
while True:
client.send(b'hello')
data = client.recv(1024)
print(data)
time.sleep(1)
server
'''
服务端的工作:
1.接收客户端的请求
2.24小时不间断提供服务
3.实现并发
'''
import socket
import time
from threading import Thread
server = socket.socket()
server.bind(
('127.0.0.1', 9527)
)
server.listen(5)
print('启动服务端...')
# 线程任务,执行接收客户端消息与发送消息给客户端
def working(conn):
while True:
try:
data = conn.recv(1024)
if len(data) == 0:
break
print(data)
time.sleep(1)
conn.send(data.upper())
except Exception as e:
print(e)
break
conn.close()
while True:
conn, addr = server.accept()
print(addr)
t = Thread(target=working, args=(conn, ))
t.start()