Python 套接字 IO 客户端发出得到一个意外的关键字参数'wait'



我正在使用RPI,VPS和socket io。我想创建一个网站,用户可以在其中单击按钮并从 pi 获取图片。我用python编写了服务器和客户端应用程序。服务器使用 Socketio + 烧瓶

server.py

from flask import Flask, request, render_template
from flask_socketio import SocketIO, rooms, join_room, leave_room
app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = 'secret!'
sio = SocketIO(app)
@app.route('/')
def index():
    """Serve the client-side application."""
    with open('index.html') as f:
        return f.read()
    # return app.send_static_file('index.html')
@sio.on('connect')
def connect():
    print('Connected:')
@sio.on('join')
def on_join(room):
    join_room(room)
    print(request.sid + ' joined room ' + room )
@sio.on('leave')
def on_leave(room):
    leave_room(room)
    print(request.sid + ' left room ' + room )
@sio.on('message')
def handle_json(message):
    # print('Received json: ')
    # print(message)
    room = rooms(request.sid)[0]
    print('Forwarding to room:', room)
    sio.send(message, room=room, skip_sid=request.sid, json=True)

if __name__ == '__main__':
    sio.run(app, host= "142.11.210.25", port = 80)

rpi_client.py

import io
import time
import picamera
import socketio
import base64
sio = socketio.Client()
# Specify the room
room = 'cam_1'
socket_url = 'http://142.11.210.25:80/'
def capture_b64_image():
    # Create an in-memory stream
    image_stream = io.BytesIO()
    # Capture image
    with picamera.PiCamera() as camera:
        # Camera warm-up time
        time.sleep(2)
        camera.capture(image_stream, 'jpeg')
    # Encode the image
    image_bytes = image_stream.getvalue()   
    return base64.b64encode(image_bytes).decode()

@sio.on('connect')
def on_connect():
    print('Connection established')
    sio.emit('join', room)
@sio.on('json')
def on_message(data):
    print('Received message:', data)
    encoded_image = capture_b64_image()
    print( len(encoded_image) )
    sio.send({'image': encoded_image})

@sio.on('disconnect')
def on_disconnect():
    print('Disconnected from server')
sio.connect(socket_url)
sio.wait()

索引.html

<!DOCTYPE html>
<html>
    <head>
        <title>SocketIO Demo</title>
    </head>
    <body>
        <img id="image-preview" src="" />
        <button id='cam_click'>Take photo</button>
        <script
            src="http://code.jquery.com/jquery-3.3.1.js"
            integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
            crossorigin="anonymous"></script>
        <script src="/static/js/socket.io.js"></script>
        <script>
            var socket = io('/');
            var room = 'cam_1';
            function bytes2ascii(bytes) {
                var str = '';
                for(var i = 0; i < bytes.length; i++) {
                    str += String.fromCharCode(bytes[i]);
                }
                return str;
            }
            socket.on('connect', function() {
                console.log(11);
                socket.emit('join', room);
            });
            socket.on('json', function (data) {
                console.log('Received:');
                console.log(data);
                // $('#cam_content').html(data.image);
                //var encoded_image = bytes2ascii(new Uint8Array(data.image) );
                var encoded_image = data.image
                $('#image-preview').attr('src', `data:image/png;base64,${encoded_image}`);
            });
            $(document).ready(function() {
                console.log('Ready...');
                $('#cam_click').click(function() {
                    socket.send('image');
                });
            });
        </script>
    </body>
</html>

当我运行服务器和 RPI 客户端时,我建立了连接,当我单击按钮在索引中拍照时.html,服务器转到 room1,我在 rpi 客户端上得到了它并拍摄了一张照片,但随后它在发送图片时崩溃并给了我类型错误:emit(( 得到一个意外的关键字参数 'wait'

这是我运行代码时得到的错误(RPI 客户端(。

Connection established
Received message: image
996008
Exception in thread Thread-5:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.5/dist-packages/socketio/client.py", line 514, in _handle_eio_message
    self._handle_event(pkt.namespace, pkt.id, pkt.data)
  File "/usr/local/lib/python3.5/dist-packages/socketio/client.py", line 413, in _handle_event
    r = self._trigger_event(data[0], namespace, *data[1:])
  File "/usr/local/lib/python3.5/dist-packages/socketio/client.py", line 455, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "rpi_client2.py", line 41, in on_message
    sio.send({'image': encoded_image})
  File "/usr/local/lib/python3.5/dist-packages/socketio/client.py", line 296, in send
    callback=callback, wait=wait, timeout=timeout)
TypeError: emit() got an unexpected keyword argument 'wait'

我按照指示安装了python-socketio[client]。

可能导致错误的原因是什么,解决方法是什么? 谢谢你,祝你有美好的一天!

根据 python-socketio 文档,https://python-socketio.readthedocs.io/en/latest/client.html#emitting-events:

为方便起见,还提供了 send(( 方法。此方法接受数据元素作为其唯一参数,并随之发出标准消息事件:

sio.send('some data'(

因此,您可以更改:

sio.send({'image': encoded_image}(

自:

sio.emit('message', {'image': encoded_image}(

相关内容

最新更新