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
asked Jan 16, 2021 at 15:53
Farhan Kabir
1692 silver badges14 bronze badges
1 Answer 1
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()
Sign up to request clarification or add additional context in comments.
1 Comment
Farhan Kabir
Thanks a lot! Actually, I tried it just now and it is working. Didn't put any delay though before
lang-py
s.sendands.recvinto a loop?while some_condition_exists: ...?