本文整理汇总了Python中uwsgi.websocket_recv_nb函数的典型用法代码示例。如果您正苦于以下问题:Python websocket_recv_nb函数的具体用法?Python websocket_recv_nb怎么用?Python websocket_recv_nb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了websocket_recv_nb函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __call__
def __call__(self, environ, start_response):
uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))
self.r = redis.StrictRedis(host=self.redis_host, port=self.redis_port, db=0)
channel = self.r.pubsub()
channel.subscribe(self.room)
websocket_fd = uwsgi.connection_fd()
redis_fd = channel.connection._sock.fileno()
core_id = environ['uwsgi.core']
self.setup(core_id)
while True:
ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0)
if not ready[0]:
uwsgi.websocket_recv_nb()
for fd in ready[0]:
if fd == websocket_fd:
try:
msg = uwsgi.websocket_recv_nb()
except IOError:
self.end(core_id)
return ""
if msg:
self.websocket(core_id, msg)
elif fd == redis_fd:
msg = channel.parse_response()
if msg[0] == 'message':
uwsgi.websocket_send(msg[2])
开发者ID:awentzonline,项目名称:SLAK,代码行数:29,代码来源:tremolo.py
示例2: chat
def chat(request):
try:
room = Room.objects.get(pk=1)
except:
room = None
uwsgi.websocket_handshake(request['HTTP_SEC_WEBSOCKET_KEY'], request.get('HTTP_ORIGIN', ''))
r = redis.StrictRedis(host='localhost', port=6379, db=0)
channel = r.pubsub()
channel.subscribe(room.name)
websocket_fd = uwsgi.connection_fd()
redis_fd = channel.connection._sock.fileno()
while True:
ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0)
if not ready[0]:
uwsgi.websocket_recv_nb()
for fd in ready[0]:
if fd == websocket_fd:
msg = uwsgi.websocket_recv_nb()
if msg:
msg = json.loads(msg)
if msg['c'] == 'm':
first_msg = "%s: %s" % (msg['u'], msg['ms'])
second_msg = None
if first_msg and not second_msg:
r.publish(room.name, first_msg)
elif second_msg and first_msg:
r.publish(room.name, "%s <br> %s" % (first_msg, second_msg))
elif fd == redis_fd:
msg = channel.parse_response()
if msg[0] == 'message':
uwsgi.websocket_send("[%s] %s" % (time.time(), msg[2]))
开发者ID:GodsOfWeb,项目名称:django-chat,代码行数:32,代码来源:views.py
示例3: websocket
def websocket():
print('im in ws')
env = request.environ
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
r = redis.StrictRedis(host='localhost', port=6379, db=0)
channel = r.pubsub()
channel.subscribe('teste_ws')
websocket_fd = uwsgi.connection_fd()
redis_fd = channel.connection._sock.fileno()
while True:
print("here in the loop")
# wait max 4 seconds to allow ping to be sent
ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0)
# send ping on timeout
if not ready[0]:
uwsgi.websocket_recv_nb()
for fd in ready[0]:
if fd == websocket_fd:
msg = uwsgi.websocket_recv_nb()
if msg:
r.publish('teste_ws', msg)
elif fd == redis_fd:
msg = channel.parse_response()
# only interested in user messages
if msg[0] == b'message':
uwsgi.websocket_send(msg[2])
开发者ID:ecostadaluz,项目名称:core,代码行数:26,代码来源:__init__.py
示例4: application
def application(env, start_response):
'''https://github.com/unbit/uwsgi/blob/master/tests/websockets_chat.py'''
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
print 'websocket relay connecting...'
r = redis.StrictRedis(host='redis', port=6379, db=0)
channel = r.pubsub()
channel.subscribe('broadcast')
websocket_fd = uwsgi.connection_fd()
redis_fd = channel.connection._sock.fileno()
while True:
# wait max 4 seconds to allow ping to be sent
ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0)
# send ping on timeout
if not ready[0]:
uwsgi.websocket_recv_nb()
for fd in ready[0]:
if fd == websocket_fd:
msg = uwsgi.websocket_recv_nb()
if msg:
r.publish('incoming', msg)
elif fd == redis_fd:
msg = channel.parse_response()
# only interested in user messages
if msg[0] == 'message':
uwsgi.websocket_send(msg[-1])
开发者ID:awentzonline,项目名称:uwsgi-websocket-redis-relay,代码行数:27,代码来源:relay.py
示例5: application
def application(e, sr):
if e['PATH_INFO'] == '/phys':
uwsgi.websocket_handshake()
w = World()
me = Box('box0', w, 1000, 250, -1000, 250, 0)
box1 = Box('box1', w, 20, 50, -1000, 250, 0)
box2 = Box('box2', w, 20, 50, -1500, 350, 0)
box3 = Box('box3', w, 20, 50, -1500, 450, 0)
box4 = Box('box4', w, 200, 150, -1500, 550, 0)
ramp = Ramp('ramp0', w, 400, 0, 100, 7000, 10, 400)
print "BOX DRAWING COMPLETE"
gevent.spawn(physic_engine, w)
ufd = uwsgi.connection_fd()
while True:
ready = gevent.select.select([ufd, w.redis_fd], [], [], timeout=4.0)
if not ready[0]:
uwsgi.websocket_recv_nb()
for fd in ready[0]:
if fd == ufd:
try:
msg = uwsgi.websocket_recv_nb()
if msg == 'fw':
orientation = me.body.getOrientation()
v = Vector3(0, 0, 5000).rotate(orientation.getAxis(), orientation.getAngle())
me.body.activate(True)
me.body.applyCentralImpulse( v )
elif msg == 'bw':
orientation = me.body.getOrientation()
v = Vector3(0, 0, -5000).rotate(orientation.getAxis(), orientation.getAngle())
me.body.activate(True)
me.body.applyCentralImpulse( v )
elif msg == 'rl':
orientation = me.body.getOrientation()
v = Vector3(0, 2000000, 0).rotate(orientation.getAxis(), orientation.getAngle())
me.body.activate(True)
me.body.applyTorqueImpulse( v )
elif msg == 'rr':
orientation = me.body.getOrientation()
v = Vector3(0, -2000000, 0).rotate(orientation.getAxis(), orientation.getAngle())
me.body.activate(True)
me.body.applyTorqueImpulse( v )
#me.body.applyForce( Vector3(0, 0, 10000), Vector3(-200, 0, 0))
#me.body.applyForce( Vector3(0, 0, -10000), Vector3(200, 0, 0))
except IOError:
import sys
print sys.exc_info()
return [""]
elif fd == w.redis_fd:
msg = w.channel.parse_response()
if msg[0] == 'message':
uwsgi.websocket_send(msg[2])
开发者ID:20tab,项目名称:robotab,代码行数:58,代码来源:bullphys.py
示例6: ws_downloads
def ws_downloads():
uwsgi.websocket_handshake()
while True:
uwsgi.websocket_recv_nb() # for close()
gevent.sleep(2)
try:
payload = json.dumps(rtorrent.downloads())
except:
payload = json.dumps({'error': "can't connect to rtorrent"})
uwsgi.websocket_send(payload)
开发者ID:RossValler,项目名称:carson,代码行数:12,代码来源:carson.py
示例7: wait_for_game
def wait_for_game(self):
while (self.game.started or self.game.finished or
self.name not in self.game.players):
gevent.sleep(1)
try:
uwsgi.websocket_recv_nb()
except IOError:
import sys
print sys.exc_info()
if self.name in self.players:
self.end('leaver')
return [""]
开发者ID:20tab,项目名称:robotab,代码行数:12,代码来源:robotab_orig.py
示例8: connect
def connect(self, app, request, user, host):
import uwsgi
uwsgi.websocket_handshake()
self.open(app=app, request=request, user=user, host=host)
try:
while True:
try:
msg = uwsgi.websocket_recv_nb()
if msg:
msg = msg.decode()
try:
msg = json.loads(msg, object_hook=json_loads_handler)
except ValueError:
msg = None
if msg:
self.process_request_from_browser(app, request, user, host, msg, uwsgi)
else:
for msg in self.messages:
uwsgi.websocket_send(json.dumps(msg, default=json_dumps_handler))
sleep(0.1)
except OSError:
raise SystemExit()
finally:
self.close(app=app, request=request, user=user, host=host)
开发者ID:ayurjev,项目名称:envi,代码行数:25,代码来源:classes.py
示例9: recv
def recv(self):
try:
data = uwsgi.websocket_recv_nb()
if data:
self.on_websocket_data(data)
except:
raise self.WebSocketError()
开发者ID:daya-prac,项目名称:djangowebsocket,代码行数:7,代码来源:view.py
示例10: websocket_view
def websocket_view(context, request):
uwsgi.websocket_handshake()
this = greenlet.getcurrent()
this.has_message = False
q_in = asyncio.Queue()
q_out = asyncio.Queue()
# make socket proxy
if inspect.isclass(view):
view_callable = view(context, request)
else:
view_callable = view
ws = UWSGIWebsocket(this, q_in, q_out)
# start monitoring websocket events
asyncio.get_event_loop().add_reader(
uwsgi.connection_fd(),
uwsgi_recv_msg,
this
)
# NOTE: don't use synchronize because we aren't waiting
# for this future, instead we are using the reader to return
# to the child greenlet.
future = asyncio.Future()
asyncio.async(
run_in_greenlet(this, future, view_callable, ws)
)
# switch to open
this.parent.switch()
while True:
if future.done():
if future.exception() is not None:
raise future.exception()
raise WebsocketClosed
# message in
if this.has_message:
this.has_message = False
try:
msg = uwsgi.websocket_recv_nb()
except OSError:
msg = None
if msg or msg is None:
q_in.put_nowait(msg)
# message out
if not q_out.empty():
msg = q_out.get_nowait()
try:
uwsgi.websocket_send(msg)
except OSError:
q_in.put_nowait(None)
this.parent.switch()
开发者ID:circlingthesun,项目名称:aiopyramid,代码行数:59,代码来源:uwsgi.py
示例11: receive
def receive(self):
if self._closed:
raise WebSocketError("Connection is already closed")
try:
return uwsgi.websocket_recv_nb()
except IOError, e:
self.close()
raise WebSocketError(e)
开发者ID:dalou,项目名称:django-flow,代码行数:8,代码来源:uwsgi_runserver.py
示例12: ws
def ws(env):
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'],
env.get('HTTP_ORIGIN', ''))
e = Event()
events.add(e)
try:
while True:
try:
uwsgi.websocket_recv_nb()
except OSError:
break
yield e.wait()
if e.event():
assets = json.dumps(['boo', 'foo'])
uwsgi.websocket_send(assets)
finally:
events.remove(e)
e.close()
开发者ID:baverman,项目名称:backup,代码行数:18,代码来源:live-server.py
示例13: websocket_read
def websocket_read(self):
try:
msg = uwsgi.websocket_recv_nb()
except Exception as e:
log.info("Websocket closed")
self.ws.close(e)
return False
if msg:
self.ws.message(msg)
return True
开发者ID:paradoxxxzero,项目名称:fawn,代码行数:10,代码来源:fawn.py
示例14: application
def application(e, sr):
if e['PATH_INFO'] == '/phys':
uwsgi.websocket_handshake()
w = World()
me = Box('box0', w, 900, 200)
me.set_pos(0, 1150, 0)
box1 = Box('box1', w, 20, 50)
box1.set_pos(0, 250, 0)
box2 = Box('box2', w, 20, 50)
box2.set_pos(0, 350, 0)
box3 = Box('box3', w, 20, 50)
box3.set_pos(0, 450, 0)
box4 = Box('box4', w, 200, 150)
box4.set_pos(0, 550, 0)
gevent.spawn(physic_engine, w)
ufd = uwsgi.connection_fd()
while True:
ready = gevent.select.select([ufd, w.redis_fd], [], [], timeout=4.0)
if not ready[0]:
uwsgi.websocket_recv_nb()
for fd in ready[0]:
if fd == ufd:
try:
msg = uwsgi.websocket_recv_nb()
if msg == 'fw':
me.body.addForce((0, 250, 0))
except IOError:
import sys
print sys.exc_info()
return [""]
elif fd == w.redis_fd:
msg = w.channel.parse_response()
if msg[0] == 'message':
uwsgi.websocket_send(msg[2])
开发者ID:20tab,项目名称:robotab,代码行数:40,代码来源:phys.py
示例15: application
def application(env, start_response):
parse = parse_qs(env['QUERY_STRING'])
if 'uid' not in parse:
print('Connection error: uid not found')
return ''
uid = parse['uid'][0]
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'],
env.get('HTTP_ORIGIN', ''))
print('Connection to websocket %s', uid)
channel = rd.pubsub()
channel.subscribe(uid)
print('Subscribe to channel %s', uid)
ws_fd = uwsgi.connection_fd()
rd_fd = channel.connection._sock.fileno()
while True:
# wait max 4 seconds to allow ping to be sent
ready = select.select([ws_fd, rd_fd], [], [], 4.0)
# send ping on timeout
if not ready[0]:
uwsgi.websocket_recv_nb()
for fd in ready[0]:
if fd == ws_fd:
try:
msg = uwsgi.websocket_recv_nb()
if msg:
print('Pub msg %s', msg)
rd.publish(uid, msg)
except IOError:
print('Websocket Closed: %s', uid)
return ''
elif fd == rd_fd:
msg = channel.parse_response()
# only interested in user messages
if msg[0] == 'message':
print('Send msg %s', msg[2])
uwsgi.websocket_send(msg[2])
开发者ID:forilen,项目名称:websocket_demo,代码行数:39,代码来源:app_srv.py
示例16: wsSubData_nb
def wsSubData_nb(self):
"""Websocket subscribe redis pubsub nonbolocking.
Keepalive websocket connection with client."""
uwsgi.websocket_handshake(self.environ['HTTP_SEC_WEBSOCKET_KEY'], self.environ.get('HTTP_ORIGIN', ''))
channel = self.r.pubsub()
channel.subscribe(self.channel)
channel.parse_response()
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:
uwsgi.websocket_recv_nb()
elif fd == redis_fd:
wsdata = channel.parse_response()[2]
uwsgi.websocket_send(wsdata)
else:
uwsgi.websocket_recv_nb()
time.sleep(1)
开发者ID:bagel,项目名称:cluster,代码行数:23,代码来源:mon.py
示例17: recv
def recv(server, sock):
while not sock.evt_open.is_set():
time.sleep(0.05)
if hasattr(server, 'on_open'):
server.on_open(self)
try:
fd = uwsgi.connection_fd()
while not sock.evt_close.is_set():
uwsgi.wait_fd_read(fd, 1.0)
uwsgi.suspend()
_fd = uwsgi.ready_fd()
msg = uwsgi.websocket_recv_nb()
if msg:
frame = (1, OP_TEXT, msg)
server.on_message(sock, frame)
finally:
sock.evt_close.set()
开发者ID:smallfz,项目名称:flask-ws,代码行数:17,代码来源:wsuwsgi.py
示例18: _start_websocket
def _start_websocket():
"""
This is the most important piece of the code. It's the only one that is allowed to use the uwsgi websocket api.
It deals with receiving:
- spawn a _listen greenlet
_ when notified that the websocket fd is ready, it will fetch the message, and push it to the right handler
and writing:
- spawns a handler whenever necessary
- when notified that a handler wants to writes, does the writing
:return:
"""
assert request.headers.get('Upgrade') == "websocket", "/websockets is only available for websocket protocol"
assert uwsgi is not None, "You must run your app using uwsgi if you want to use the /websockets route"
env = request.headers.environ
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) # engage in websocket
_websocket_handlers['_websocket_listen'] = spawn(_listen, uwsgi.connection_fd()) # Spawn greenlet that will listen to fd
while True:
ready = wait([_websocket_send_event, _websocket_recv_event], None, 1) # wait for events
if ready: # an event was set
if ready[0] == _websocket_recv_event:
try:
msg = uwsgi.websocket_recv_nb()
except IOError:
_kill_all()
return
if msg:
json_msg = json.loads(msg)
handler = _websocket_handlers[json_msg['namespace']]
handler.go(json_msg)
_websocket_recv_event.clear()
elif ready[0] == _websocket_send_event: # One or more handlers requested a message to be sent
while True:
try:
msg = _websocket_send_queue.get_nowait()
except Empty:
break
uwsgi.websocket_send(json.dumps(msg))
_websocket_send_event.clear()
开发者ID:mehdigmira,项目名称:flask-gevent-uwsgi-websockets,代码行数:40,代码来源:__init__.py
示例19: wait
def wait(self):
"""Waits and returns received messages.
If running in compatibility mode for older uWSGI versions,
it also sends messages that have been queued by send().
A return value of None means that connection was closed.
This must be called repeatedly. For uWSGI < 2.1.x it must
be called from the main greenlet."""
while True:
if self._req_ctx is not None:
try:
msg = uwsgi.websocket_recv(request_context=self._req_ctx)
except IOError: # connection closed
return None
return self._decode_received(msg)
else:
# we wake up at least every 3 seconds to let uWSGI
# do its ping/ponging
event_set = self._event.wait(timeout=3)
if event_set:
self._event.clear()
# maybe there is something to send
msgs = []
while True:
try:
msgs.append(self._send_queue.get(block=False))
except gevent.queue.Empty:
break
for msg in msgs:
self._send(msg)
# maybe there is something to receive, if not, at least
# ensure uWSGI does its ping/ponging
try:
msg = uwsgi.websocket_recv_nb()
except IOError: # connection closed
self._select_greenlet.kill()
return None
if msg: # message available
return self._decode_received(msg)
开发者ID:Melvie,项目名称:BeerShed,代码行数:38,代码来源:async_gevent_uwsgi.py
示例20: websockets_wrapper
def websockets_wrapper(environ, start_response):
handler = self.routes.get(environ['PATH_INFO'])
if not handler:
return app(environ, start_response)
# do handshake
uwsgi.websocket_handshake(
environ['HTTP_SEC_WEBSOCKET_KEY'],
environ.get('HTTP_ORIGIN', ''))
# setup events
send_event = Event()
send_queue = Queue(maxsize=1)
recv_event = Event()
recv_queue = Queue(maxsize=1)
# create websocket client
wfd = uwsgi.connection_fd()
client = self.create_worker(
environ, wfd, send_event, send_queue, recv_event, recv_queue)
# spawn handler
handler = spawn(handler, client)
# spawn recv listener
def listener(client):
ready = select([client.fd], [], [], client.timeout)
recv_event.set()
listening = spawn(listener, client)
while True:
if not client.connected:
recv_queue.put(None)
listening.kill()
handler.join(client.timeout)
return ''
# wait for event to draw our attention
ready = wait([handler, send_event, recv_event], None, 1)
# handle send events
if send_event.is_set():
try:
uwsgi.websocket_send(send_queue.get())
send_event.clear()
except IOError:
client.connected = False
# handle receive events
elif recv_event.is_set():
recv_event.clear()
try:
recv_queue.put(uwsgi.websocket_recv_nb())
listening = spawn(listener, client)
except IOError:
client.close()
self.unregister_worker(client)
# handler done, we're outta here
elif handler.ready():
listening.kill()
return ''
开发者ID:novareto,项目名称:uvclight,代码行数:64,代码来源:websockets.py
注:本文中的uwsgi.websocket_recv_nb函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论