server.py
import socket
import time
import threading
sock = socket.socket()
sock.bind(('127.0.0.1', 9006))
sock.listen()
def socket_recv_handle(client_socket):
while True:
r = client_socket.recv(1024)
print(client_socket.getpeername())
print('recv: ', r)
def socket_send_handle(client_socket):
cnt = 1
while True:
print(cnt)
client_socket.send(b'server %d' % cnt)
cnt += 1
print('send: ', client_socket.getpeername())
time.sleep(1)
while True:
client_sock, client_addr = sock.accept()
# 使用多线程,对阻塞式socket进行读写分离,避免读取时候一直被阻塞
threading.Thread(target=socket_send_handle, args=(client_sock,)).start()
threading.Thread(target=socket_recv_handle, args=(client_sock,)).start()
client01.py
import socket
import time
sock = socket.socket()
sock.connect(('127.0.0.1', 9006))
cnt = 1
while True:
print(sock.recv(1024))
sock.send(b'client 01, cnt %d' % cnt)
cnt += 1
print(cnt)
time.sleep(1)
client02.py
import socket
import time
sock = socket.socket()
sock.connect(('127.0.0.1', 9006))
cnt = 1
while True:
print(sock.recv(1024))
sock.send(b'client 02, cnt %d' % cnt)
cnt += 1
print(cnt)
time.sleep(3)
server.py日志
client01.py 日志
client02.py日志