Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
<input value="invia" type="button">
<div style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto" id="blackboard">
</div>
""" % (ws_scheme, env['HTTP_HOST'])
elif env['PATH_INFO'] == '/foobar/':
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
print "websockets..."
while True:
msg = uwsgi.websocket_recv_nb()
if msg:
queue.put(msg)
else:
try:
wait_read(uwsgi.connection_fd(), 0.1)
except gevent.socket.timeout:
try:
msg = queue.get_nowait()
uwsgi.websocket_send(msg)
except Exception:
pass
return ""
print("websockets...")
# a future for waiting for redis connection
f = GreenFuture()
asyncio.Task(redis_subscribe(f))
# the result() method will switch greenlets if needed
subscriber = f.result()
# open another redis connection for publishing messages
f0 = GreenFuture()
t = asyncio.Task(redis_open(f0))
connection = f0.result()
myself = greenlet.getcurrent()
myself.has_ws_msg = False
# start monitoring websocket events
asyncio.get_event_loop().add_reader(uwsgi.connection_fd(), ws_recv_msg, myself)
# add a 4 seconds timer to manage ping/pong
asyncio.get_event_loop().call_later(4, ws_recv_msg, myself)
# add a coroutine for redis messages
f = GreenFuture()
asyncio.Task(redis_wait(subscriber, f))
# switch again
f.greenlet.parent.switch()
while True:
# any redis message in the queue ?
if f.done():
msg = f.result()
uwsgi.websocket_send("[%s] %s" % (time.time(), msg))
""" % (ws_scheme, env['HTTP_HOST'])
if sys.version_info[0] > 2:
return output.encode('latin1')
return output
elif env['PATH_INFO'] == '/favicon.ico':
return ""
elif env['PATH_INFO'] == '/foobar/':
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
print("websockets...")
r = redis.StrictRedis(host='localhost', port=6379, db=0)
channel = r.pubsub()
channel.subscribe('foobar')
websocket_fd = uwsgi.connection_fd()
redis_fd = channel.connection._sock.fileno()
while True:
uwsgi.wait_fd_read(websocket_fd, 3)
uwsgi.wait_fd_read(redis_fd)
uwsgi.suspend()
fd = uwsgi.ready_fd()
if fd > -1:
if fd == websocket_fd:
msg = uwsgi.websocket_recv_nb()
if msg:
r.publish('foobar', msg)
elif fd == redis_fd:
msg = channel.parse_response()
print(msg)
# only interested in user messages
r = redis.StrictRedis(
host=os.environ['TAILER_REDIS_HOST'],
port=os.environ['TAILER_REDIS_PORT'],
db=os.environ['TAILER_REDIS_DATABASE'])
uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'],
environ.get('HTTP_ORIGIN', ''))
# Emit the backlog of messages
lines = r.lrange(task_uuid, 0, -1)
send_message('message', ''.join(lines))
channel = r.pubsub()
channel.subscribe(task_uuid)
channel_socket_fd = channel.connection._sock.fileno()
websocket_fd = uwsgi.connection_fd()
while True:
rlist, _, _ = gevent.select.select(
[channel_socket_fd, websocket_fd], [], [], 5.0)
if rlist:
for fd in rlist:
if fd == channel_socket_fd:
message = channel.parse_response()
# See http://redis.io/topics/pubsub for format of `message`
if message[0] == 'message':
send_message('message', message[2])
elif fd == websocket_fd:
# Let uwsgi do it's job to receive pong and send ping
uwsgi.websocket_recv_nb()
else:
# Have not heard from channel and client in 5 seconds...
def get_file_descriptor(self):
"""Return the file descriptor for the given websocket"""
try:
return uwsgi.connection_fd()
except IOError, e:
self.close()
raise WebSocketError(e)
def get_request_socket(self, env):
if not self.ca:
return None
sock = None
if env.get('uwsgi.version'): # pragma: no cover
try:
import uwsgi
fd = uwsgi.connection_fd()
conn = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
try:
sock = socket.socket(_sock=conn)
except:
sock = conn
except Exception as e:
pass
elif env.get('gunicorn.socket'): # pragma: no cover
sock = env['gunicorn.socket']
if not sock:
# attempt to find socket from wsgi.input
input_ = env.get('wsgi.input')
if input_:
if hasattr(input_, '_sock'): # pragma: no cover
raw = input_._sock
def __init__(self, environ, start_response, application):
self.environ = environ
self.socket = socket.fromfd(uwsgi.connection_fd(), socket.AF_INET, socket.SOCK_STREAM)
self.rfile = makefile(self.socket)
self.application = application
self.start_response = start_response
self.request_version = environ['SERVER_PROTOCOL']
def __call__(self, environ, start_response):
self._sock = uwsgi.connection_fd()
self.environ = environ
uwsgi.websocket_handshake()
self._req_ctx = None
if hasattr(uwsgi, 'request_context'):
# uWSGI >= 2.1.x with support for api access across-greenlets
self._req_ctx = uwsgi.request_context()
else:
# use event and queue for sending messages
from gevent.event import Event
from gevent.queue import Queue
from gevent.select import select
self._event = Event()
self._send_queue = Queue()