1、简单介绍
socketio:与websocket对比
2、server
Attach the Socket.IO server to an application sanic
import socketio
from sanic import Sanic
sio = socketio.AsyncServer(async_mode='sanic', cors_allowed_origins=[])
@sio.event
async def connect(sid, environ):
print('connect ', sid)
@sio.on('message')
async def my_message(sid, data):
print('message ', data)
@sio.event
async def disconnect(sid):
print('disconnect ', sid)
if __name__ == '__main__':
app = Sanic(__name__)
app.config['CORS_SUPPORTS_CREDENTIALS'] = True
sio.attach(app)
app.run(host="0.0.0.0", port=5050)
3、同步client
import socketio
sio = socketio.Client()
@sio.event
def connect():
print('connection established')
@sio.event
def my_message(data):
print('message received with ', data)
sio.emit('my response', {'response': 'my response'})
@sio.event
def disconnect():
print('disconnected from server')
sio.connect('http://localhost:5050')
4、异步client (asyncio)
import asyncio
import socketio
sio = socketio.AsyncClient()
@sio.event
async def connect():
print('connection established')
@sio.event
async def my_message(data):
print('message received with ', data)
await sio.emit('my response', {'response': 'my response'})
@sio.event
async def disconnect():
print('disconnected from server')
async def main():
await sio.connect('http://127.0.0.1:5050')
await sio.wait()
asyncio.get_event_loop().run_until_complete(main())
5、坑
特别注意版本匹配问题: