本文整理汇总了Python中uwsgi.websocket_handshake函数的典型用法代码示例。如果您正苦于以下问题:Python websocket_handshake函数的具体用法?Python websocket_handshake怎么用?Python websocket_handshake使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了websocket_handshake函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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]))
示例2: __call__
def __call__(self, environ, start_response):
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()
# spawn a select greenlet
def select_greenlet_runner(fd, event):
"""Sets event when data becomes available to read on fd."""
while True:
event.set()
select([fd], [], [])[0]
self._select_greenlet = gevent.spawn(
select_greenlet_runner,
uwsgi.connection_fd(),
self._event)
return self.app(self)
示例3: 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])
示例4: connect
def connect(self, app, request, user, host):
# noinspection PyUnresolvedReferences
import uwsgi
import json
uwsgi.websocket_handshake()
self.open(app=app, request=request, user=user, host=host)
try:
while True:
try:
msg = uwsgi.websocket_recv()
except OSError:
raise SystemExit()
msg = msg.decode()
msg = json.loads(msg)
if "action" in msg:
ws_request = Request(msg, environ=request.environ)
pipe = RequestPipe()
result = pipe.process(self, app, ws_request, user, host)
if isinstance(result, dict):
result.update({"ws": {"event": msg["action"]}})
if isinstance(result, (bytes, bytearray)):
uwsgi.websocket_send(result)
else:
uwsgi.websocket_send(
json.dumps(result, default=json_dumps_handler)
if isinstance(result, (list, dict))
else str(result)
)
self.tick(app=app, request=ws_request, user=user, host=host)
finally:
self.close(app=app, request=request, user=user, host=host)
示例5: wsData
def wsData(self):
"""Websocket redis hget"""
uwsgi.websocket_handshake(self.environ['HTTP_SEC_WEBSOCKET_KEY'], self.environ.get('HTTP_ORIGIN', ''))
codes = []
while True:
t = str(int(time.time()))
legend = []
data = []
keys = sorted(self.r.keys("sum_*"))
for code in codes:
key = '_'.join(["sum", code])
legend.append("")
if self.r.hexists(key, t):
data.append(int(self.r.hget(key, t)))
else:
data.append(0)
for key in keys:
code = key.split('_')[-1]
if self.r.hexists(key, t) and code not in codes:
codes.append(code)
data.append(int(self.r.hget(key, t)))
legend.append(code)
if not data:
time.sleep(2)
continue
wsdata = {
"data": data,
"legend": legend
}
uwsgi.websocket_send(json.JSONEncoder().encode(wsdata))
time.sleep(2)
示例6: 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)
示例7: init_container
def init_container():
host = request.environ.get('HTTP_HOST', '')
uwsgi.websocket_handshake()
while True:
req = uwsgi.websocket_recv()
#print('REQ', req)
req = json.loads(req)
if req['state'] == 'done':
break
client_id = req.get('id')
if not client_id:
client_id = dc.add_new_client()
client_id, queue_pos = dc.am_i_next(client_id)
if queue_pos < 0:
resp = do_init(req['browser'], req['url'], req['ts'], host)
else:
resp = {'queue': queue_pos, 'id': client_id}
resp = json.dumps(resp)
#print('RESP', resp)
uwsgi.websocket_send(resp)
print('ABORTING')
示例8: 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])
示例9: __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])
示例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()
示例11: application
def application(env, start_response):
if env['PATH_INFO'] == "/ws/":
uwsgi.websocket_handshake(env.get('HTTP_SEC_WEBSOCKET_KEY', ''), env.get('HTTP_ORIGIN', ''))
while True:
msg = uwsgi.websocket_recv()
uwsgi.websocket_send(msg)
else:
return get_wsgi_application()(env, start_response)
示例12: 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])
示例13: application
def application(env, sr):
ws_scheme = "ws"
if "HTTPS" in env or env["wsgi.url_scheme"] == "https":
ws_scheme = "wss"
if env["PATH_INFO"] == "/":
sr("200 OK", [("Content-Type", "text/html")])
return """
<html>
<head>
<script language="Javascript">
var s = new WebSocket("%s://%s/foobar/");
s.onopen = function() {
alert("connected !!!");
s.send("ciao");
};
s.onmessage = function(e) {
var bb = document.getElementById('blackboard')
var html = bb.innerHTML;
bb.innerHTML = html + '<br/>' + e.data;
};
s.onerror = function(e) {
alert(e);
}
s.onclose = function(e) {
alert("connection closed");
}
function invia() {
var value = document.getElementById('testo').value;
s.send(value);
}
</script>
</head>
<body>
<h1>WebSocket</h1>
<input type="text" id="testo"/>
<input type="button" value="invia" onClick="invia();"/>
<div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
</div>
</body>
</html>
""" % (
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()
uwsgi.websocket_send("[%s] %s" % (time.time(), msg))
示例14: application
def application(env, sr):
ws_scheme = 'ws'
if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https':
ws_scheme = 'wss'
if env['PATH_INFO'] == '/':
sr('200 OK', [('Content-Type','text/html')])
return """
<html>
<head>
<script language="Javascript">
var s = new WebSocket("%s://%s/foobar/");
s.onopen = function() {
alert("connected !!!");
s.send("ciao");
};
s.onmessage = function(e) {
var bb = document.getElementById('blackboard')
var html = bb.innerHTML;
bb.innerHTML = html + '<br/>' + e.data;
};
s.onerror = function(e) {
alert(e);
}
s.onclose = function(e) {
alert("connection closed");
}
function invia() {
var value = document.getElementById('testo').value;
s.send(value);
}
</script>
</head>
<body>
<h1>WebSocket</h1>
<input type="text" id="testo"/>
<input type="button" value="invia" onClick="invia();"/>
<div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
</div>
</body>
</html>
""" % (ws_scheme, env['HTTP_HOST'])
elif env['PATH_INFO'] == '/foobar/':
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
print "websockets..."
uwsgi.websocket_channel_join('room001')
while True:
msg = uwsgi.websocket_recv()
print len(msg)
#uwsgi.websocket_send("hello %s = %s" % (time.time(), msg))
uwsgi.channel_send('room001', "channel %s = %s" % (time.time(), msg))
示例15: application
def application(env, sr):
"""The main entry
"""
# Get websocket scheme
wsScheme = 'ws'
if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https':
wsScheme = 'wss'
# The path info
if env['PATH_INFO'] == '/':
sr('200 OK', [ ('Content-Type', 'text/html' ) ])
return """
<html>
<head>
<script language="Javascript">
var s = new WebSocket("%s://%s/foobar/");
s.onopen = function() {
alert("connected !!!");
s.send("ciao");
};
s.onmessage = function(e) {
var bb = document.getElementById('blackboard')
var html = bb.innerHTML;
bb.innerHTML = html + '<br/>' + e.data;
};
s.onerror = function(e) {
alert(e);
}
s.onclose = function(e) {
alert("connection closed");
}
function invia() {
var value = document.getElementById('testo').value;
s.send(value);
}
</script>
</head>
<body>
<h1>WebSocket</h1>
<input type="text" id="testo"/>
<input type="button" value="invia" onClick="invia();"/>
<div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
</div>
</body>
</html>
""" % (wsScheme, env['HTTP_HOST'])
elif env['PATH_INFO'] == '/foobar/':
uwsgi.websocket_handshake()
print 'Start a web socket connection'
while True:
msg = uwsgi.websocket_recv()
uwsgi.websocket_send("Server receive [%s] %s" % (time.time(), msg))
print 'Close a web socket connection'