最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Flask-SocketIO测试出错:WebSocket connection to failed Error during WebSocket handshake Unexpected response code 400

Flask crifan 7559浏览 0评论

折腾:

【已解决】flask中实现websocket

期间,继续去测试

结果用:

flask-socketio

/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/RunningFast-Server/runningfast/templates/index.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
<script>
$(document).ready(function(){
    var socket = io.connect(‘http://’ + document.domain + ‘:’ + location.port + ‘/test’);
    socket.on(‘my response’, function(msg) {
        $(‘#log’).append(‘<p>Received: ‘ + msg.data + ‘</p>’);
    });
    $(‘form#emit’).submit(function(event) {
        socket.emit(‘my event’, {data: $(‘#emit_data’).val()});
        return false;
    });
    $(‘form#broadcast’).submit(function(event) {
        socket.emit(‘my broadcast event’, {data: $(‘#broadcast_data’).val()});
        return false;
    });
});
</script>
</head>
<body>
    <h1>Flask-SocketIO Test</h1>
    <h2>Send:</h2>
    <table>
        <tr>
            <td>
                <form id="emit" method=’POST’ action=’#’>
                    <textarea name="emit_data" id="emit_data"></textarea>
                    <div><input type="submit" value="Emit"></div>
                </form>
            </td>
            <td>
                <form id="broadcast" method=’POST’ action=’#’>
                    <textarea name="broadcast_data" id="broadcast_data"></textarea>
                    <div><input type="submit" value="Broadcast"></div>
                </form>
            </td>
        </tr>
    </table>
    <h2>Receive:</h2>
    <div id="log"></div>
</body>
</html>

加上对应的代码:

/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/RunningFast-Server/runningfast/app.py

from flask import render_template
from flask_socketio import SocketIO, emit
@socketio.on(‘my event’, namespace=’/test’)
def test_message(message):
    gLog.debug("message=%s", message)
    emit(‘my response’, {‘data’: message[‘data’]})
@socketio.on(‘my broadcast event’, namespace=’/test’)
def test_message(message):
    gLog.debug("message=%s", message)
    emit(‘my response’, {‘data’: message[‘data’]}, broadcast=True)
@socketio.on(‘connect’, namespace=’/test’)
def test_connect():
    gLog.debug("connect")
    emit(‘my response’, {‘data’: ‘Connected’})
@socketio.on(‘disconnect’, namespace=’/test’)
def test_disconnect():
    gLog.debug("Client disconnected")
@app.route(‘/’)
def index():
    return render_template(‘index.html’)

然后运行出错:

socket.io.min.js:2 WebSocket connection to ‘ws://115.29.173.126:21085/socket.io/?EIO=3&transport=websocket&sid=1eaac006a2004bf785dc6abf2e9cfe86’ failed: Error during WebSocket handshake: Unexpected response code: 400
socket.io.min.js:1 POST http://115.29.173.126:21085/socket.io/?EIO=3&transport=polling&t=1477642747986-1&sid=1eaac006a2004bf785dc6abf2e9cfe86 400 (BAD REQUEST)
socket.io.min.js:1 GET http://115.29.173.126:21085/socket.io/?EIO=3&transport=polling&t=1477642764226-8 net::ERR_EMPTY_RESPONSE

然后,终于有log输出了:

<div–<——————————————————————————
DEBUG in app [/root/RunningFast/staging/runningfast/app.py:181]:
connect

<div–<——————————————————————————

[2016-10-28 16:19:22 +0000] [29294] [CRITICAL] WORKER TIMEOUT (pid:29325)
[2016-10-28 16:19:22 +0000] [29325] [INFO] Worker exiting (pid: 29325)
[2016-10-28 16:19:22 +0000] [29337] [INFO] Booting worker with pid: 29337

<div–<——————————————————————————

DEBUG in app [/root/RunningFast/staging/runningfast/app.py:80]:
app=<Flask ‘runningfast.app’>, api=<flask_restful.Api object at 0x7f05f1f101d0>, redis_store=<flask_redis.FlaskRedis object at 0x7f05f06ad950>, db=<SQLAlchemy engine=’mysql://runningfast:Jiandao123@localhost/runningfast_dev’>, server_mode=staging, server_type=develop, rq=<flask_rq2.app.RQ object at 0x7f05f1f10610>, socketio=<flask_socketio.SocketIO object at 0x7f05f1f10990>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in app [/root/RunningFast/staging/runningfast/app.py:200]:
API_VERSION=1.0, API_URL_PREFIX=/runningfast/api/v1.0, OPEN_API_URL_PREFIX=/runningfast/api/v1.0/open

<div–<——————————————————————————

[2016-10-28 16:19:23 +0000] [29319] [ERROR] Socket error processing request.
Traceback (most recent call last):
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 135, in handle
    self.handle_request(listener, req, client, addr)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 191, in handle_request
    six.reraise(*sys.exc_info())
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 183, in handle_request
    resp.close()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 418, in close
    self.send_headers()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 338, in send_headers
    util.write(self.sock, util.to_bytestring(header_str, "ascii"))
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gunicorn/util.py", line 302, in write
    sock.sendall(data)
  File "/usr/local/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
  File "/usr/local/lib/python2.7/socket.py", line 174, in _dummy
    raise error(EBADF, ‘Bad file descriptor’)
error: [Errno 9] Bad file descriptor

Socket error processing request error Errno 9 Bad file descriptor

Flask-SocketIO Socket error processing request error Errno 9 Bad file descriptor

Python socket (Socket Error Bad File Descriptor) – Stack Overflow

python socket.error: [Errno 9] Bad file descriptor – Stack Overflow

[ERROR] Socket error processing request. · Issue #160 · miguelgrinberg/Flask-SocketIO · GitHub

确定是gunicorn, eventlet and gevent的问题。。。

当 socket 被关闭时,会报错 "error: [Errno 9] Bad file descriptor" · Issue #3 · duanhongyi/dwebsocket · GitHub

Eventlet worker raises error: [Errno 9] Bad file descriptor on pypy · Issue #602 · benoitc/gunicorn · GitHub

发生python socket.error: [Errno 9] Bad file descriptor,是什么原因? – 知乎

WebSocket connection to ‘ws://115.29.173.126:21085/socket.io/?EIO=3&transport=websocket&sid=1334737c86bb4105b5a3ef858cd9d8c9’ failed: WebSocket is closed before the connection is established.

然后又出现其它错误:

socket.io.min.js:1 GET http://115.29.173.126:21085/socket.io/?EIO=3&transport=polling&t=1477645166484-114&sid=d458460494464830919e01657cc9347c net::ERR_EMPTY_RESPONSE
socket.io.min.js:2 WebSocket connection to ‘ws://115.29.173.126:21085/socket.io/?EIO=3&transport=websocket&sid=2ac882f253a542eca75990148f1a4237’ failed: Error during WebSocket handshake: Unexpected response code: 400

Flask-SocketIO Error during WebSocket handshake Unexpected response code 400

heroku – Flask-SocketIO Error during websocket handshake Unexpected response code: 400 – Stack Overflow

Error during WebSocket handshake: Unexpected response code: 400 · Issue #1942 · socketio/socket.io · GitHub

说是要去修改nginx的配置

-》感觉不像啊。。。

Flask-SocketIO failed: WebSocket is closed before the connection is established

failed: WebSocket is closed before the connection is established. · Issue #298 · miguelgrinberg/Flask-SocketIO · GitHub

->

换成:

gevent就好了?

那去试试:

先去用:

pip uninstall eventlet

卸载eventlet

再去用:

pip install gevent

安装gevent

(RunningFast) ➜  staging pip uninstall eventlet
Uninstalling eventlet-0.19.0:
  /root/Envs/RunningFast/lib/python2.7/site-packages/eventlet/wsgi.pyc
Proceed (y/n)? y
  Successfully uninstalled eventlet-0.19.0
(RunningFast) ➜  staging pip install gevent
Collecting gevent
  Using cached gevent-1.1.2-cp27-cp27m-manylinux1_x86_64.whl
Requirement already satisfied (use –upgrade to upgrade): greenlet>=0.4.9 in /root/Envs/RunningFast/lib/python2.7/site-packages (from gevent)
Installing collected packages: gevent
Successfully installed gevent-1.1.2

结果好像真的没有那些:

failed: WebSocket is closed before the connection is established.

failed: Error during WebSocket handshake: Unexpected response code: 400

了,

不过还有些其它错误:

【未解决】Flask-SocketIO测试出错:POST socket.io EIO 400 BAD REQUEST

【总结】

此处,测试Flask-SocketIO出现错误:

socket.io.min.js:1 GET http://115.29.173.126:21085/socket.io/?EIO=3&transport=polling&t=1477645166484-114&sid=d458460494464830919e01657cc9347c net::ERR_EMPTY_RESPONSE
socket.io.min.js:2 WebSocket connection to ‘ws://115.29.173.126:21085/socket.io/?EIO=3&transport=websocket&sid=2ac882f253a542eca75990148f1a4237’ failed: Error during WebSocket handshake: Unexpected response code: 400

最终靠:

把eventlet换成gevent,就解决了此问题:

pip uninstall eventlet
pip install gevent

此处,列出目前的包,供参考:

(RunningFast) ➜  staging pip list                                                     
alembic (0.8.8)
aniso8601 (1.1.0)
click (6.6)
croniter (0.3.12)
enum34 (1.1.6)
Flask (0.11.1)
Flask-HTTPAuth (3.2.1)
Flask-Login (0.3.2)
Flask-Migrate (2.0.0)
Flask-Redis (0.3.0)
Flask-RESTful (0.3.5)
Flask-RQ2 (16.1.1)
Flask-Script (2.0.5)
Flask-SocketIO (2.7.1)
Flask-SQLAlchemy (2.1)
gevent (1.1.2)
greenlet (0.4.10)
gunicorn (19.6.0)
itsdangerous (0.24)
Jinja2 (2.8)
Mako (1.0.4)
MarkupSafe (0.23)
meld3 (1.0.2)
MySQL-python (1.2.5)
pip (8.1.2)
python-dateutil (2.5.3)
python-editor (1.0.1)
python-engineio (1.0.3)
python-socketio (1.6.0)
pytz (2016.6.1)
redis (2.10.5)
rq (0.6.0)
rq-scheduler (0.7.0)
setuptools (28.0.0)
six (1.10.0)
SQLAlchemy (1.1.1)
supervisor (3.3.1)
Werkzeug (0.11.11)
wheel (0.30.0a0)

转载请注明:在路上 » 【已解决】Flask-SocketIO测试出错:WebSocket connection to failed Error during WebSocket handshake Unexpected response code 400

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.172 seconds, using 22.21MB memory