当服务器 运行 来自一个函数时,为什么 eventlet/socketio 不工作?

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

下面的代码按预期工作并且 运行s 没有问题:

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

但是,一旦最后一行被函数包裹,就会发生错误

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

这是完整的错误信息:

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

我该如何防止这种情况发生?我正在构建一个小型聊天应用程序,为了保持整洁,我需要从一个函数(特别是 class 方法)中创建并 运行 服务器。

问题出在这一行:

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

这一行应该是:

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

更新代码:

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

输出:

解释:

eventlet.listen()eventlet.wsgi.server()parameventlet.listen()表示监听哪个地址和端口

('', 8000)结合了地址和端口。如果我们不设置第一个参数,它将默认为 0.0.0.0.

如果我们设置 localhost 它将是回溯地址 127.0.0.1 我们也可以设置我们计算机的 IP 地址。