gpt4 book ai didi

websocket - Bottle +WebSocket

转载 作者:行者123 更新时间:2023-12-03 06:38:10 31 4
gpt4 key购买 nike

是否可以在同一应用程序(同一端口)中托管一个普通 Bottle 应用程序和一个 WebSocket 应用程序(例如: https://github.com/defnull/bottle/blob/master/docs/async.rst )?这样/ws 将转到 WebSocket 处理程序,而所有其他处理程序将正常路由到其他 Bottle 处理程序。

最佳答案

确实如此。

服务器:

#!/usr/bin/python

import json
from bottle import route, run, request, abort, Bottle ,static_file
from pymongo import Connection
from gevent import monkey; monkey.patch_all()
from time import sleep

app = Bottle()

@app.route('/websocket')
def handle_websocket():
wsock = request.environ.get('wsgi.websocket')
if not wsock:
abort(400, 'Expected WebSocket request.')
while True:
try:
message = wsock.receive()
wsock.send("Your message was: %r" % message)
sleep(3)
wsock.send("Your message was: %r" % message)
except WebSocketError:
break

@app.route('/<filename:path>')
def send_html(filename):
return static_file(filename, root='./static', mimetype='text/html')


from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketHandler, WebSocketError

host = "127.0.0.1"
port = 8080

server = WSGIServer((host, port), app,
handler_class=WebSocketHandler)
print "access @ http://%s:%s/websocket.html" % (host,port)
server.serve_forever()

包含 javascript 的 html 页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8080/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
</script>
</head>
<body>
</body>
</html>

客户:

#!/usr/bin/python

from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Reeiving..."
result = ws.recv()
print "Received '%s'" % result
ws.close()

关于websocket - Bottle +WebSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10316374/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com