I'm using a gevent StreamServer to handle incoming connections from clients.
After the clients are connected, the client will send some messages to the server, and the server will process it. Everything works fine on this side. But now and then the server would also send messages back to specific client.
I would do this with redis. I created a queue with a specific client id as key. After the client send a message, I check the queue and if there is any message, I send it back to the client.
The disadvantage of this approach is, the server can only send the message AFTER the client send a message.
Is there a way I could both wait for incoming data and redis blpop, so I can send the message back to client as soon as the message is ready, instead of waiting until the client sends the next data?
import gevent
from gevent import socket
from gevent.server import StreamServer
import redis
r = redis.Redis('localhost')
def handle_echo(sock, address):
fp = sock.makefile()
while True:
line = fp.readline()
if line:
client_id = line.split(",")[0]
if r.llen('%s:servercmds' % client_id) > 0:
tosend = r.lrange('%s:servercmds' % imei, 0, 0)[0]
try:
fp.write(tosend)
fp.flush()
r.lpop('%s:servercmds' % imei)
except:
print('cannot send data to client')
else:
break
sock.shutdown(socket.SHUT_WR)
sock.close()
server = StreamServer(('', 8045), handle_echo, spawn=10000)
server.serve_forever()