如何解决如果未建立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>
未建立连接时是否可以向前端发送消息?
解决方法
Websocket的设计不容易中止。后端代码需要断开连接,或者Websocket只是等待套接字打开,然后继续正常运行,直到消息通过为止。
但是,您的代码中没有任何东西表明发生了错误或建立或断开连接时,看起来好像一旦建立连接,它将立即发送“ Hello,World”,然后将其收到两次,间隔3秒
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。