当我在浏览器中加载客户端时,控制台每隔几秒就会输出以下错误:
index.js:83 GET http://localhost:8080/ws/?EIO=3&transport=polling&t=MEzMuny 404 (Not Found)
,它将打印以下消息:
18:08:56 127.0.0.1 [01/Jun/2018:22:08:56 +0000] "GET /ws/?EIO=3&transport=polling&t=MEzPODJ HTTP/1.1" 404 172 "http://localhost:8080/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
这是服务器代码:
async def hello(request):
return web.FileResponse('./hello.html')
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
else:
await ws.send_str(msg.data + '/answer')
elif msg.type == aiohttp.WSMsgType.ERROR:
print('ws connection closed with exception %s' % ws.exception())
return ws
app = web.Application()
app.add_routes([
web.get('/', hello),
web.get('/ws', websocket_handler)
])
web.run_app(app)
客户端代码,通过默认路由提供:
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script>
const socket = io('http://localhost:8080', {path: '/ws'});
console.log(socket)
socket.on('connect', function(){
console.log('connected')
});
</script>
<body></body>
</html>
感谢您的关注。
答案 0 :(得分:0)
显然socket.io不会用aiohttp玩球。将客户端实现更改为WebSocket解决了这个问题:
const socket = new WebSocket(`ws://${window.location.host}/ws`)
socket.onopen = () => { console.log('connected') }
socket.onmessage = event => { console.log(event.data) }
socket.onclose = () => { console.log('disconnected') }