Skip to content
Advertisement

How to create a continuously running socket client in python

I have been using TCP socket for a while now in python and my socket client closes after sending a message but I want to create a continuously running socket client that will keep sending messages as I already have a continuously running listener server. So the socket client code which I like to work on is below:

import socket

TCP_IP = "0.0.0.0"
TCP_PORT = 5003

BUFFER_SIZE = 1024

array = [0, 5, 10, 15]
print("Sending sensor value",array)

MESSAGE = bytearray(array)  # converting to bytearray for sending via socket

# Sending via socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((TCP_IP,TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

please advise

Advertisement

Answer

Try this:

import socket
import time

TCP_IP = "0.0.0.0"
TCP_PORT = 5003

BUFFER_SIZE = 1024

array = [0, 5, 10, 15]


MESSAGE = bytearray(array)  # converting to bytearray for sending via socket

# Sending via socket
while True:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((TCP_IP,TCP_PORT))
    s.send(MESSAGE)
    data = s.recv(BUFFER_SIZE)
    print("Sending sensor value",array)
    time.sleep(3)
    s.close()
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement