sainc + socketio 客户端服务器通信

1、简单介绍

sainc学习教程

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、坑

        特别注意版本匹配问题:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值