【发布时间】:2021-02-27 15:12:39
【问题描述】:
我需要一个使用 python 运行的 socket.io 服务器。 我按照这个例子:
https://tutorialedge.net/python/python-socket-io-tutorial/
最终文件如下:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button onClick="sendMsg()">Hit Me</button>
<!--WORKS:-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>-->
<!-- DOESNT WORK:-->
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
const socket = io("http://localhost:8080");
function sendMsg() {
socket.emit("message", "HELLO WORLD");
}
socket.on("message", function(data) {
console.log(data);
});
</script>
</body>
</html>
server.py
> from aiohttp import web
import socketio
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
async def index(request):
with open('index.html') as f:
return web.Response(text=f.read(), content_type='text/html')
@sio.on('message')
async def print_message(sid, message):
print("Socket ID-: " , sid)
print(message)
await sio.emit('message', message[::-1])
app.router.add_get('/', index)
if __name__ == '__main__':
web.run_app(app)
这只是复制粘贴,因此工作正常,但我不想使用来自某些在线资源的脚本。因此,我尝试通过注释掉正在运行的版本并将其替换为使用本地 socket.io.js 的版本来修改脚本的 src。 由于我没有在我的机器上找到脚本,我发现了以下问题,这两个问题都没有帮助我解决我的问题:
node-js-socket-io-socket-io-js-not-found
socket-io-not-being-served-by-node-js-server
无论我做什么,我的浏览器都会出现以下错误:
GET http://localhost:8080/node_modules/socket.io/socket.io.js net::ERR_ABORTED 404(未找到)
(index):18 Uncaught ReferenceError: io is not defined 在(索引):18 (匿名)@(索引):18
根据我从 2 个链接线程的理解,我的服务器应该在服务器上调用 listen 时提供 socket.io/socket.io.js。 不幸的是,我的情况并没有发生这种情况。
我通过 pip 安装了 socket.io,我还按照建议尝试了 npm install socket.io --save,这给了我一个新文件夹“node_modules”,但是将脚本的 src 修改为:
<script src="http://localhost:8080/node_modules/socket.io/socket.io.js"></script>
也无济于事。
出于某种原因,使用 cdnjs 中的 fie 可以正常工作(请参阅我的 index.html)。
如果有人能帮我解决这个问题,我会很高兴。
干杯 克里斯
【问题讨论】:
标签: javascript python socket.io