Click here to Skip to main content
15,078,444 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have done socket programming in python for my TCP based device now I want to send data to mqtt broker from this socket program so I tried to do my program like this but I am not able to connect to the broker can anyone help me to find out what mistake I am making.

What I have tried:

<pre>import socket
from obd_data import packet_splitter
HOST = ''  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

import paho.mqtt.client as mqtt
import time
import random
import json
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    conn, addr = s.accept()
        client = mqtt.Client(str(addr))  # create new instance
        client.connect(broker_ip, broker_port, 60)  # connect to broker
        print("not connected to mqtt")
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            a= data.hex().upper()
            topic = "device/{}/message".format(client)
            payload = {
                "param1": a,
            if client.is_connected():
                client.publish(topic, json.dumps(payload))
                print("{} - message sent: {} - {}".format(client, topic, json.dumps(payload)))
                print("{} is not connected to the broker!".format(client))

            if not data:

Updated 4-Aug-21 20:30pm
Richard MacCutchan 5-Aug-21 3:24am
Are you sure the server is running, and listening on that port?

1 solution

Um ... are you sure about that IP address? is the loopback IP address also called "localhost". The address is used to establish an IP connection to the same machine or computer being used by the end-user.

So it's unlikely to be the one you need ... and you shouldn't hard-code connection addresses anyway!
Mohammed Khalifa 2021 5-Aug-21 3:13am
yes I have my MQTT server and TCP client on same machine

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900