Python-socketio:如何从服务器向客户端发出消息?

时间:2019-02-15 06:20:48

标签: python python-3.x python-2.7 python-sockets python-socketio

在服务器上,由于eventlet.wsgi.server(eventlet.listen(('', 5000)), app)被阻止,因此下一行sio.emit('message', "hello")不运行。如何从服务器向客户端发送消息?我需要创建另一个线程吗?

我的服务器代码:

import socketio
import engineio
import eventlet

sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
})

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

@sio.on('message')
def message(sid, data):
    print('message ', data)

@sio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
    sio.emit('message', "hello")

我的客户代码:

import socketio

sio = socketio.Client()

@sio.on('connect')
def on_connect():
    print('connection established')

@sio.on('message')
def on_message(data):
    print('message received with ', data)
    sio.emit('my response', {'response': 'my response'})

@sio.on('disconnect')
def on_disconnect():
    print('disconnected from server')

sio.connect('http://localhost:5000')
sio.emit('message',"this is my first message")

1 个答案:

答案 0 :(得分:0)

您有两个选择:

  1. 将发射添加到connect处理程序中,以便它在每次新客户端连接到服务器时运行。

  2. 启动后台任务,然后再启动服务器并从那里开始。

相关问题