如何在python-socketio中从python服务器向javascript客户端发出消息? [英] How to emit message from python server to javascript client in python-socketio?

查看:30
本文介绍了如何在python-socketio中从python服务器向javascript客户端发出消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

socketio 客户端成功连接到服务器并向服务器发送带有 emit 的消息,但另一方向服务器到客户端失败.我找不到错误的来源.这是

The socketio client successfully connects to the server and sends messages with emit to the server but the other direction server to the client fails. I cannot find the source of error. It is

这里是基于 python 示例的 app.py 中的服务器 python-socketio 网站:

Here is the server python in app.py based on the example in python-socketio website:

from aiohttp import web
import socketio

sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)

async def index(request):
    """Serve the client-side application."""
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

@sio.on('connect', namespace='/chat')
def connect(sid, environ):
    print("connect", sid)

@sio.on('chat message', namespace='/chat')
async def message(sid, data):
    print("server received message!", data)
    await sio.emit('reply', data)
    await sio.send(data)

@sio.on('disconnect', namespace='/chat')
def disconnect(sid):
    print('disconnect', sid)

app.router.add_static('/static', 'static')
app.router.add_get('/', index)

if __name__ == '__main__':
    web.run_app(app)

我尝试评论 await sio.emit('reply', data)await sio.send(data) 之一,但结果是一样的.这是 index.html 中的 javascript 客户端:

I tried commenting one of await sio.emit('reply', data) or await sio.send(data) but result was the same. Here is the javascript client in index.html:

<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
  </head>
  <body>
    <form id="the_form">
      <input type="input" name="msg" id="msg"></input>
      <input type="submit" value="➤"></input>
    </form>
    <script>
      var socket = io('http://localhost:8080/chat');

      socket.on('connect', function(){console.log('connect!')});
      socket.on('message', function(msg){console.log('message!', msg)});
      socket.on('disconnect', function(){console.log('disconnect!')});
      socket.on('reply', function(msg){console.log('reply!', msg)});

      document.getElementById('the_form').onsubmit = function(e) {
        let msg = document.getElementById('msg').value;
        document.getElementById('msg').value = '';

        // send it to the server
        socket.emit('chat message', msg);

        return false
      };
    </script>
  </body>
</html>

在终端窗口中,我运行服务器.然后,我打开两个浏览器窗口(Chrome 版本 69.0.3497.100(官方版本)(64 位))并从其中一个发送测试".这是我在每个窗口上看到的:

On the terminal window, I run the server. Then, I open two browser windows (Chrome Version 69.0.3497.100 (Official Build) (64-bit)) and send 'test' from one of them. Here is what I see on each window:

终端

$ python3 app.py 
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
connect 9b18034f7b8b4d4c857dec394ef01429
connect 3adea48a3e00459f807855da0337599c
server received message! test

窗口 1(控制台日志)

connect!

窗口 2(控制台日志)

connect!

推荐答案

基于示例 此处 建议在 evgeni-fotia 的评论,这里需要命名空间参数.似乎默认命名空间,至少在这个版本中,不是异步函数的命名空间.因此,使用回显消息广播的正确方法如下:

Based on the examples here suggested in comments by evgeni-fotia, the namespace argument is necessary here. It seems the default namespace, at least on this version, is not the namespace of the async function. So, the correct way to broadcast with echo back a message is the following:

@sio.on('chat message', namespace='/chat')
async def message(sid, data):
    print("server received message!", data)
    await sio.emit('reply', data, namespace='/chat')

这篇关于如何在python-socketio中从python服务器向javascript客户端发出消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆