1

I need to get a socket.io server running using python. I followed this example:

https://tutorialedge.net/python/python-socket-io-tutorial/

With the final files looking as follows:

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

So much this is only copy paste and thus works fine, but I dont want to use the script from some online source. So I tried to modify the src of the script by commenting out the running version and replacing it by a version using a local socket.io.js. As I did not find the script on my machine I found the following questions, that both did not help me solve my issue:

node-js-socket-io-socket-io-js-not-found

socket-io-not-being-served-by-node-js-server

No matter what I do I get the following error in my browser:

GET http://localhost:8080/node_modules/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)

(index):18 Uncaught ReferenceError: io is not defined at (index):18 (anonymous) @ (index):18

From what I understood from the 2 linked threads, my server should provide the socket.io/socket.io.js when listen is called on the server. Unfortunately this is not happening in my case.

I had socket.io installed via pip, I also tried npm install socket.io --save as suggested, this gives me a new folder 'node_modules', but modifying the src for my script to:

<script src="http://localhost:8080/node_modules/socket.io/socket.io.js"></script>

doesnt help either.

For some reason using the fie from cdnjs works just fine (see my index.html).

I would be very glad if someone could help me out with this.

Cheers Chris

christian
  • 110
  • 1
  • 2
  • 15

1 Answers1

2

I've never worked with AIOHTTP (always worked with flask-socketio) so I did some research using the documentation. It turns out that like a lot of http server, AIOHTTP doesn't serve static files out of the box.
You will thus need to take care of it using the add_static method (doc here).
(Note that if you want to deploy this app for production it would be better practice to use an HTTP server like Apache or Nginx).
Just add this line under your routes declarations.

app.router.add_static('/static/', path='static/')

Now you need to create a static folder in the root of your project and put your socket.io.js file inside of it. Make sure that the socket.io.js in the version 2.2 (same as the CDN version). You can get this file by downloading it directly from the CDN URL you were using or using npm -i -s socket.io-client@2.2. You can then find the socket.io.js file in node_modules/socket.io-client/dist.

You now just need to use <script src="/static/socket.io.js"></script> in your HTML to import socket.io.

S. Ferard
  • 221
  • 2
  • 9
  • I also tested using an apache webserver provided via xampp. This unfortunately did not make any difference. I tested your suggestion and at least I get different errors now: Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer'). at Request.onLoad (http://localhost:8080/static/socket.io.js:3994:27) at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8080/static/socket.io.js:3889:20) – christian Nov 18 '20 at 08:09
  • and: DevTools failed to load SourceMap: Could not load content for http://localhost:8080/static/socket.io.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE – christian Nov 18 '20 at 08:09
  • 1
    I faced the same error while trying to find an answer to your question. Are you sure that socket.io.js is the version 2.2 over socket.io-client ? – S. Ferard Nov 18 '20 at 08:13
  • Pip list says: python-socketio 4.6.0. However I used a socket.io.js from a previous npm installation. I unsinstalled npm and changed the js to a copy of the one from the onlinesource that works. Copying this now leaves me with only one error: DevTools failed to load SourceMap: Could not load content for http://localhost:8080/static/socket.io.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE Looks like we are getting close – christian Nov 18 '20 at 08:19
  • UPDATE: It seems to only be a warning, communication works like a gem now. Thank you so much for your help! – christian Nov 18 '20 at 08:26
  • 1
    Awesome, happy to help ! source maps files are not mandatory, just useful to debug sometimes (more [here](https://www.html5rocks.com/en/tutorials/developertools/sourcemaps/)). If you want to silence this warning you can either add the socket.io.js.map in the static folder (you can download it with the same CDN url adding ".map" at the end) or edit socket.io.js and delete the last line `# sourceMappingURL=socket.io.js.map` – S. Ferard Nov 18 '20 at 08:42
  • 1
    Funny, but the last line in the socket.io.js was already commented out. I just added the socket.io.js.map and the warning is gone as you suggested. Im now going to study the links you provided, always like additional information. Thank you so much. – christian Nov 18 '20 at 08:54