# TCP connection between Node RED and Python Code for sending and receiveing messages

**URL:** <https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308>\
**Category:** General\
**Created:** [4 September 2022 11:33 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308 "2022-09-04T11:33:04Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![KerimFry](https://avatars.discourse-cdn.com/v4/letter/k/13edae/32.png) [@KerimFry](https://discourse.nodered.org/u/KerimFry)\
**Post date:** [4 September 2022 11:33 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/1 "2022-09-04T11:33:04Z")

</div>

Hi there.  
I was trying to build a flow that would communicate with my python script through Node RED by using TCP sockets. I tried many of the nodes such as TCP in, TCP out or TCP request node to communicate with the python script that acts as a server. However, even if I am able to send a message by using TCP out node from client, I am not able to receive messages from server to Node Red. Is there a way to communicate between Node RED and Python Script so that I can both send and receive messages between client and server? I tried using TCP request node as well but couldn't achieve it. Below I share you the python script as well as the Node RED Flow

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/0/e/0ef56af244d1ffe23496495c089486a9ed836485.png)

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/1/5/15d284e1c1eb81cd58c9d4db1cd886b7f80627c6.png)

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [4 September 2022 12:04 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/2 "2022-09-04T12:04:00Z")

</div>

I prefer mqtt for such things. It is usually easier.

---

<div class="post-metadata">

**Author:** ![ghayne](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/ghayne/32/39_2.png) [@ghayne](https://discourse.nodered.org/u/ghayne)\
**Post date:** [4 September 2022 15:22 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/3 "2022-09-04T15:22:39Z")

</div>

+1 for MQTT, much easier.

---

<div class="post-metadata">

**Author:** ![dceejay](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/dceejay/32/38_2.png) [@dceejay](https://discourse.nodered.org/u/dceejay)\
**Post date:** [4 September 2022 15:30 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/4 "2022-09-04T15:30:15Z")

</div>

The TCP request node should do what you want in that case as it can wait for a reply - but you may need to set either a timeout for the response - or maybe a trigger character (often \n) and add that to your replay - or have some way of knowing when it has finished sending...

(and I assume you don't have a firewall blocking network access ?)

If you attach the code as a snippet rather than an image we can try it out.

---

<div class="post-metadata">

**Author:** ![KerimFry](https://avatars.discourse-cdn.com/v4/letter/k/13edae/32.png) [@KerimFry](https://discourse.nodered.org/u/KerimFry)\
**Post date:** [5 September 2022 13:29 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/5 "2022-09-05T13:29:39Z")

</div>

I will check it out Colin and ghayne, thank you for your reply. However for now if I succeed I prefer using TCP socket. Thanks for your advices though

---

<div class="post-metadata">

**Author:** ![KerimFry](https://avatars.discourse-cdn.com/v4/letter/k/13edae/32.png) [@KerimFry](https://discourse.nodered.org/u/KerimFry)\
**Post date:** [5 September 2022 13:44 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/6 "2022-09-05T13:44:10Z")

</div>

Sure I can directly put the code for both my flow and the pyscript that will be used on this reply. I do not have any firewall blocking the network access since the server and the client can connect to each other. Again thank you for your consideration. Do you mean I need to put a trigger node and set it to character "/n" ? Again thank you for your reply. Below are the codes.

Server.py:

```auto
import socket

HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 64746 # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print(f"Connected by {addr}")
        str = ""
        data = ""
        while str != "exit":
            data = conn.recv(1024)
            str = data.decode("utf-8")
            #What I want to do from here is as the signal from Node RED is arrived, I want to do some process and as the process is finished, I want to let Node RED know that the process is finished by sending a message called achieved
            reply= "achieved"
            conn.send(reply.encode())
            print(str)
            if not data:
                break
            conn.sendall(data)
        conn.close()

```

Node RED Flow:

```auto
[
    {
        "id": "6f73fac4aa181732",
        "type": "debug",
        "z": "b9693f9a4e361253",
        "name": "Sensor Status",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 560,
        "y": 60,
        "wires": []
    },
    {
        "id": "3897194dea65fdd5",
        "type": "switch",
        "z": "b9693f9a4e361253",
        "name": "",
        "property": "payload",
        "propertyType": "msg",
        "rules": [
            {
                "t": "eq",
                "v": "0",
                "vt": "num"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 1,
        "x": 350,
        "y": 140,
        "wires": [
            [
                "6f73fac4aa181732",
                "8651cc4d2dcd497a",
                "72ebbbcacb5d1263"
            ]
        ]
    },
    {
        "id": "1efbbf34633117d7",
        "type": "exec",
        "z": "b9693f9a4e361253",
        "command": "another python script will be run here (if the response from the client is arrived, there won't be a need for delay)",
        "addpay": "",
        "append": "",
        "useSpawn": "false",
        "timer": "",
        "winHide": false,
        "oldrc": false,
        "name": "",
        "x": 520,
        "y": 340,
        "wires": [
            [
                "da3fed5189ea65cc",
                "a52eab2db2a0a00b"
            ],
            [],
            []
        ]
    },
    {
        "id": "8651cc4d2dcd497a",
        "type": "tcp out",
        "z": "b9693f9a4e361253",
        "name": "",
        "host": "localhost",
        "port": "64746",
        "beserver": "client",
        "base64": false,
        "end": false,
        "tls": "",
        "x": 890,
        "y": 80,
        "wires": []
    },
    {
        "id": "72ebbbcacb5d1263",
        "type": "delay",
        "z": "b9693f9a4e361253",
        "name": "",
        "pauseType": "delay",
        "timeout": "5",
        "timeoutUnits": "seconds",
        "rate": "1",
        "nbRateUnits": "1",
        "rateUnits": "second",
        "randomFirst": "1",
        "randomLast": "5",
        "randomUnits": "seconds",
        "drop": false,
        "allowrate": false,
        "outputs": 1,
        "x": 600,
        "y": 200,
        "wires": [
            [
                "1efbbf34633117d7"
            ]
        ]
    },
    {
        "id": "bc1a0afecafef991",
        "type": "inject",
        "z": "b9693f9a4e361253",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "0",
        "payloadType": "str",
        "x": 170,
        "y": 180,
        "wires": [
            [
                "3897194dea65fdd5"
            ]
        ]
    },
    {
        "id": "b2d2509b1bd940e4",
        "type": "inject",
        "z": "b9693f9a4e361253",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "1",
        "payloadType": "str",
        "x": 170,
        "y": 100,
        "wires": [
            [
                "3897194dea65fdd5"
            ]
        ]
    },
    {
        "id": "fd45d06d5159715d",
        "type": "comment",
        "z": "b9693f9a4e361253",
        "name": "If the sensor signal becomes 0, the signal will be sent to TCP socket where server.py will receive the message",
        "info": "",
        "x": 430,
        "y": 20,
        "wires": []
    },
    {
        "id": "fad549e21dd9e6e8",
        "type": "comment",
        "z": "b9693f9a4e361253",
        "name": "as the process of the python script is finished, it will return a signal to NODE Red that the process is finished and will continue to the flow",
        "info": "",
        "x": 1150,
        "y": 140,
        "wires": []
    },
    {
        "id": "a52eab2db2a0a00b",
        "type": "debug",
        "z": "b9693f9a4e361253",
        "name": "Output",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1030,
        "y": 300,
        "wires": []
    },
    {
        "id": "da3fed5189ea65cc",
        "type": "ui_text",
        "z": "b9693f9a4e361253",
        "group": "86bacf060d19c531",
        "order": 1,
        "width": 0,
        "height": 0,
        "name": "",
        "label": "Result:",
        "format": "{{msg.payload}}",
        "layout": "row-center",
        "className": "",
        "x": 1040,
        "y": 260,
        "wires": []
    },
    {
        "id": "86bacf060d19c531",
        "type": "ui_group",
        "name": "Default",
        "tab": "df9d9f57c2e7029e",
        "order": 1,
        "disp": true,
        "width": "6",
        "collapse": false,
        "className": ""
    },
    {
        "id": "df9d9f57c2e7029e",
        "type": "ui_tab",
        "name": "Home",
        "icon": "dashboard",
        "disabled": false,
        "hidden": false
    }
]

```

---

<div class="post-metadata">

**Author:** ![dceejay](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/dceejay/32/38_2.png) [@dceejay](https://discourse.nodered.org/u/dceejay)\
**Post date:** [5 September 2022 14:39 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/7 "2022-09-05T14:39:43Z")

</div>

This seems to work

```auto
[{"id":"6f73fac4aa181732","type":"debug","z":"1f7f9c4efc1c5c0a","name":"Sensor Status","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":590,"y":780,"wires":[]},{"id":"3897194dea65fdd5","type":"switch","z":"1f7f9c4efc1c5c0a","name":"","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"0","vt":"num"}],"checkall":"true","repair":false,"outputs":1,"x":380,"y":860,"wires":[["6f73fac4aa181732","3934aebde5866d5d"]]},{"id":"bc1a0afecafef991","type":"inject","z":"1f7f9c4efc1c5c0a","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"0","payloadType":"str","x":200,"y":840,"wires":[["3897194dea65fdd5"]]},{"id":"b2d2509b1bd940e4","type":"inject","z":"1f7f9c4efc1c5c0a","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"1","payloadType":"str","x":205,"y":900,"wires":[["3897194dea65fdd5"]]},{"id":"3934aebde5866d5d","type":"tcp request","z":"1f7f9c4efc1c5c0a","name":"","server":"127.0.0.1","port":"64746","out":"sit","ret":"string","splitc":" ","newline":"","trim":false,"tls":"","x":640,"y":870,"wires":[["d4b6412383796591"]]},{"id":"d4b6412383796591","type":"debug","z":"1f7f9c4efc1c5c0a","name":"Output","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":845,"y":870,"wires":[]}]

```

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/7/f/7fac1b83cf291758ff2ef06a5e11f816d1ab45ed.png)

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/8/4/84c7582ff615b6e08579a374b3964f288f856896.png)

---

<div class="post-metadata">

**Author:** ![KerimFry](https://avatars.discourse-cdn.com/v4/letter/k/13edae/32.png) [@KerimFry](https://discourse.nodered.org/u/KerimFry)\
**Post date:** [5 September 2022 15:45 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/8 "2022-09-05T15:45:27Z")

</div>

Thank you very much dceejay! It works perfectly. You are the best.  
Cheers

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [19 September 2022 15:46 UTC](https://discourse.nodered.org/t/tcp-connection-between-node-red-and-python-code-for-sending-and-receiveing-messages/67308/9 "2022-09-19T15:46:15Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
