2

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

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

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)orawait sio.send(data)但结果是一样的。这是 javascript 客户端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 位))并从其中一个窗口发送“测试”。这是我在每个窗口上看到的内容:

终端

$ 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!
4

1 回答 1

1

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

@sio.on('chat message', namespace='/chat')
async def message(sid, data):
    print("server received message!", data)
    await sio.emit('reply', data, namespace='/chat')
于 2018-10-13T10:36:15.743 回答