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

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

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

+1 for MQTT, much easier.

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.

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

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:

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:

[
    {
        "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
    }
]

This seems to work

[{"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

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