简体   繁体   中英

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

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: 在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM