gevent版
代码
server
root@iZ947mgy3c5Z:/prodata/scripts
import sys
import time
import gevent
from gevent import socket, monkey
monkey.patch_all()
def handler_request(client_sock):
while True:
data = client_sock.recv(1024)
if not data:
client_sock.close()
break
print('[{}] Recv: {}'.format(time.strftime('%Y-%m-%d %H:%M:%S'), data))
client_sock.send(data)
def server(port):
server_socket = socket.socket()
server_socket.bind(('127.0.0.1', port))
server_socket.listen(5)
while True:
client_socket, client_addr = server_socket.accept()
gevent.spawn(handler_request, client_socket)
if __name__ == '__main__':
server(7788)
client
root@iZ947mgy3c5Z:/prodata/scripts
from socket import *
from multiprocessing import Pool, current_process
from threading import Thread, current_thread
import time
host_port = ('127.0.0.1', 7788)
def worker():
try:
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(host_port)
while True:
time.sleep(1)
client_socket.send('hi'.encode())
print('[{}]: {}'.format(time.strftime("%Y-%m-%d %H:%M:%S"), current_thread().name))
finally:
client_socket.close()
def main():
t1 = Thread(target=worker, name="t1")
t2 = Thread(target=worker, name="t2")
t3 = Thread(target=worker, name="t3")
t4 = Thread(target=worker, name="t4")
t1.start()
t2.start()
t3.start()
t4.start()
if __name__ == '__main__':
main()
效果
server
root@iZ947mgy3c5Z:/prodata/scripts
[2018-01-25 14:22:40] Recv: b'hi'
[2018-01-25 14:22:40] Recv: b'hi'
[2018-01-25 14:22:40] Recv: b'hi'
[2018-01-25 14:22:40] Recv: b'hi'
[2018-01-25 14:22:41] Recv: b'hi'
[2018-01-25 14:22:41] Recv: b'hi'
[2018-01-25 14:22:41] Recv: b'hi'
[2018-01-25 14:22:41] Recv: b'hi'
[2018-01-25 14:22:42] Recv: b'hi'
[2018-01-25 14:22:42] Recv: b'hi'
[2018-01-25 14:22:42] Recv: b'hi'
[2018-01-25 14:22:42] Recv: b'hi'
[2018-01-25 14:22:43] Recv: b'hi'
[2018-01-25 14:22:43] Recv: b'hi'
[2018-01-25 14:22:43] Recv: b'hi'
[2018-01-25 14:22:43] Recv: b'hi'
client
root@iZ947mgy3c5Z:/prodata/scripts
[2018-01-25 14:22:40]: t1
[2018-01-25 14:22:40]: t2
[2018-01-25 14:22:40]: t3
[2018-01-25 14:22:40]: t4
[2018-01-25 14:22:41]: t1
[2018-01-25 14:22:41]: t2
[2018-01-25 14:22:41]: t3
[2018-01-25 14:22:41]: t4
[2018-01-25 14:22:42]: t1
[2018-01-25 14:22:42]: t2
[2018-01-25 14:22:42]: t4
[2018-01-25 14:22:42]: t3
[2018-01-25 14:22:43]: t1
[2018-01-25 14:22:43]: t2
[2018-01-25 14:22:43]: t3
[2018-01-25 14:22:43]: t4