python - 如果未建立 Web 套接字连接,如何发送消息或中止到 http 错误页面?
问题描述
下面的示例取自他们的文档并稍作修改。为什么在未建立 Web 套接字连接时它不中止?
#!/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='./', 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()
<!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>
未建立连接时是否可以向前端发送消息?
解决方案
Websockets 被设计成不会轻易中止。后端代码需要中断连接,或者 websocket 只是等待套接字打开并在消息通过时正常继续。
但是,您的代码中没有任何内容表明出现问题或者连接建立或断开时,它看起来就像一旦建立连接就会立即发送“Hello, World”,然后每隔 3 秒接收两次。
推荐阅读
- python - RuntimeError 过滤权重低于阈值的边缘 - Networkx
- java - 无法在 Java 中从 int 转换为 Integer
- spyder - 通过 VPN 启动 Spyder IDE 时出现错误“LoadLibrary failed with error 126: The module could not be found”
- ios - 无法分配“字符串”类型的值?键入“UILabel?”
- python - MariaDB 游标无法正确使用 Python
- google-cloud-platform - 如果我正在设计一个应该搜索标签/列的应用程序,我将如何在 Bigtable 中设计一个行键?
- google-kubernetes-engine - 从另一个 GKE 私有集群访问私有 GKE 集群中的节点端口服务
- python - Python(熊猫):如何根据列中的值将每一行除以“绝对”行
- python - 不同维数组之间的numpy加法
- go - golang helloworld 打印出奇怪的错误信息