如何在python-socketio中将消息从python服务器发送到javascript客户端?

时间:2018-10-12 23:31:20

标签: javascript python websocket socket.io python-socketio

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

根据python-socketio网站上的示例,这是app.py中的服务器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)await sio.send(data)中的一个,但结果相同。这是index.html中的javascript客户端:

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

1 个答案:

答案 0 :(得分:0)

根据here中建议的示例comments by evgeni-fotia,此处需要使用namespace参数。似乎至少在此版本上,默认名称空间不是async函数的名称空间。因此,通过回显消息进行广播的正确方法如下:

<html>

  <head>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-2.0.3.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
   
  <body>
     <div id="accordion">
      <h3>Section 1 - Open</h3>
      <div>
        <p>
        Paragraph 1
        </p>
      </div>
      <h3>Section 2</h3>
      <div>
        <p>
        Paragraph 2
        </p>
      </div>
    </div>
  </body>
 
</html>