0

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
5
  • 2
    Have you tried putting s.send and s.recv into a loop? Commented Jan 16, 2021 at 15:56
  • while some_condition_exists: ... ? Commented Jan 16, 2021 at 15:57
  • Did you see the examples at the end of the socket documentation?? Commented Jan 16, 2021 at 16:02
  • There are quite a few questions and answers on SO searching with your question. Do any of them answer your question? If so, let us know and we will mark yours as a duplicate. Commented Jan 16, 2021 at 16:07
  • @mkrieger1 yes I did. it workes but after some time my Linux freezes. That is why I was looking for all possible ways. Commented Jan 16, 2021 at 16:14

1 Answer 1

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()
answered Jan 16, 2021 at 16:21
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Actually, I tried it just now and it is working. Didn't put any delay though before

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.