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!
最佳答案
基于示例 here建议 comments by 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')
关于javascript - 如何在 python-socketio 中将消息从 python 服务器发送到 javascript 客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52788198/