ThatCoolCoder
ThatCoolCoder

Reputation: 288

Why does eventlet/socketio not work when the server is run from a function?

The code below works as expected and runs without problem:

import socketio
import eventlet

port = 5000
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={})

@sio.event
def connect(sid, environ):
    print('Connect')

eventlet.wsgi.server(eventlet.listen(('', port)), app) # Note this line

However, as soon as the final line is wrapped in a function, an error occurs

import socketio
import eventlet

port = 5000
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={})

@sio.event
def connect(sid, environ):
    print('Connect')

def run():
    eventlet.wsgi.server(eventlet.listen('', port), app) # Note this line

run()

This is the full error message:

Traceback (most recent call last):
  File "/home/thatcoolcoder/coding/micro-chat/tester3.py", line 16, in <module>
    run()
  File "/home/thatcoolcoder/coding/micro-chat/tester3.py", line 14, in run
    eventlet.wsgi.server(eventlet.listen('', port), app)
  File "/usr/lib/python3.9/site-packages/eventlet/convenience.py", line 49, in listen
    sock = socket.socket(family, socket.SOCK_STREAM)
  File "/usr/lib/python3.9/site-packages/eventlet/greenio/base.py", line 136, in __init__
    fd = _original_socket(family, *args, **kwargs)
  File "/usr/lib/python3.9/socket.py", line 232, in __init__
    _socket.socket.__init__(self, family, type, proto, fileno)
OSError: [Errno 97] Address family not supported by protocol

How can I prevent this? I'm building a small chat app and to keep things clean, I need to create and run the server from within a function (specifically a class method).

Upvotes: 1

Views: 1665

Answers (1)

Sabil
Sabil

Reputation: 4510

The issue is in this line:

eventlet.wsgi.server(eventlet.listen('', port), app)

This line should be:

eventlet.wsgi.server(eventlet.listen(('', port)), app)

Updated Code:

import socketio
import eventlet

port = 5000
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={})

@sio.event
def connect(sid, environ):
    print('Connect')


def run():
    eventlet.wsgi.server(eventlet.listen(('', port)), app) # Note this line

run()

Output: enter image description here

Explanation:

The eventlet.listen() is a param of eventlet.wsgi.server(), and the eventlet.listen() means listen which address and port.

The ('', 8000) combine the address and port. If we do not set the first param, it will be default 0.0.0.0.

If we set the localhost it will be look back address 127.0.0.1 and we also can set a IP address of our computer.

Upvotes: 3

Related Questions