首页 > 解决方案 > 如果未建立 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>

未建立连接时是否可以向前端发送消息?

标签: pythonwebsocketbottlegevent

解决方案


Websockets 被设计成不会轻易中止。后端代码需要中断连接,或者 websocket 只是等待套接字打开并在消息通过时正常继续。

但是,您的代码中没有任何内容表明出现问题或者连接建立或断开时,它看起来就像一旦建立连接就会立即发送“Hello, World”,然后每隔 3 秒接收两次。


推荐阅读