python练习1

本文介绍了如何使用Python和PahoMQTT客户端库,通过MQTT协议发送JSON文本、文件(包括JSON和图片)、以及语音信息到指定主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import base64

import paho.mqtt.client as mqtt
import time
import bs4
ip = '192.168.17.128'
port = 1883
messagejson = {'a': 'asdshd', 'b': 2334}
def on_connect(clinet, userdata, flag, rc):
    print(rc)
# 发送json文字
def sendjsonmessage():
    client.publish('hello', str(messagejson))
# 发送json文件
def sendjsonfilemessage():
    with open('train.jsonl', 'r', encoding='utf8') as jsonfp:
        a = jsonfp.readlines()
        for line in a:
            client.publish('hello', str(line))
            print(str(line))
# 发送图片信息
def sendjpgfile():
    # with open('')
    with open('1.jpg', 'rb') as jpgfile:
        client.publish('hello', base64.b64encode(jpgfile.read()).decode('utf-8'))
# 发送语音
def sendvoice():
    with open('received_voice.wav', 'rb') as voicefp:
        file = voicefp.read()
        client.publish('hello', base64.b64encode(file).decode('utf-8'))
client = mqtt.Client()
client.on_connect = on_connect
client.connect(ip, port, 60)
client.loop_start()
try:
    while True:
        time.sleep(1)
        # 发送json文字
        # sendjsonmessage()

        # sendjsonfilemessage()

        # 发送声音信息
        # sendvoice()

        # 发送图片信息
        sendjpgfile()
        break


except KeyboardInterrupt:
    client.loop_stop()
    client.disconnect()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值