python小技巧大应用--用aiohttp实现Websocket C/S收发JSON数据

既然aiohttp也能实现Websocket,那就直接测试应用一下吧

1)先写个服务端test_aiohttp_WSServer.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test aiohttp Websocket Server '

__author__ = 'TianJiang Gui'

import aiohttp
from aiohttp import web
import json

async def hello(request):
    return web.Response(text="Hello, world")

async def websocket_handler(request):

    # ws对象
    ws = web.WebSocketResponse()
    # 等待用户连接
    await ws.prepare(request)

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            if msg.data == 'close':
                await ws.close()
            else:
                #---gtj 注意如果带中文的显示内容
                print('msg.data:',type(msg.data),msg.data)
                jddd=json.loads(msg.data)
                #---gtj 如果带中文就显示正确了
                print('jddd',type(jddd),jddd)
                #---gtj str转换dict
                dicts = eval(jddd)
                #---gtj 从json中获取数据
                name = dicts['name']
                age = dicts['age']
                await ws.send_str('[%s]:%s 你好'%(name,age))
                print('dicts:',type(dicts),dicts)

        elif msg.type == aiohttp.WSMsgType.ERROR:
            print('ws connection closed with exception %s' % ws.exception())

    # 断开连接了
    print('websocket connection closed')
    return ws

if __name__ == '__main__':
    app = web.Application()
    app.add_routes([web.get('/', hello)])
    app.add_routes([web.get('/ws', websocket_handler)])

    web.run_app(app,host='127.0.0.1',port=8900)

代码中注意中文问题:

2)再写个客户端test_aiohttp_WSClient.py用于测试

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test aiohttp Websocket Client '

__author__ = 'TianJiang Gui'

import aiohttp
from aiohttp import web
import asyncio

import json

async def callback(msg):
    print('callback:',msg)

async def websocket(session,url):
    params = {'name': '桂天江', 'age': '33'}
    async with session.ws_connect(url) as ws:
        #---gtj 一定注意中文发送前要采用ensure_ascii=False
        jsondata=json.dumps(params,ensure_ascii=False)
        print('send jsondata:',type(jsondata),jsondata,type(params),params)
        await ws.send_json(jsondata)
        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                await callback(msg.data)
            elif msg.type == aiohttp.WSMsgType.CLOSED:
                break
            elif msg.type == aiohttp.WSMsgType.ERROR:
                break
        await ws.close()

async def main(app):
    session = aiohttp.ClientSession()
    await websocket(session,'http://127.0.0.1:8900/ws')

if __name__ == '__main__':
    app = web.Application()
    asyncio.run(main(app))

 此处要注意中文发送前的转换

最后看看运行结果吧:

服务端: 

 客户端:

最后总结:希望此文能帮到正在苦于寻找没有完整的客户端/服务端案例的你

其他前置基础文章请参见:

python小技巧大应用--用aiohttp实现HTTP C/S收发JSON数据

python小技巧大应用--用aiohttp实现HTTP C/S应用小测试

写文不易,请多关注,点赞

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿桂天山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值