代码之家  ›  专栏  ›  技术社区  ›  Muposat

AIOHTTPS服务器不与套接字通信。io客户端,错误404

  •  0
  • Muposat  · 技术社区  · 6 年前

    当我在浏览器中加载客户端时,console每隔几秒钟就会打印以下错误:

    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>
    

    感谢您的关注。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Muposat    6 年前

    显然是插座。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') }