I need to catch incoming data from tcp socket at any time and then execute a python script on my Raspberry Pi. How do I do that? I hope that you understand what i need to do.
-
1There are plenty of tutorials on the www to do what you want. Perhaps try one and let us know if you have a problem. – joan Dec 20 '14 at 20:51
Have you considered putting the TCP socket receive code inside your Python script?
Or you can just write another Python script that does a socket create, socket listen, and socket receive before calling your other Python script.
Here is some of the code to do this from http://pymotw.com/2/socket/tcp.html:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
# substitute the TCP port you want to listen on for 10000 below
server_address = ('', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'Data received - starting other Python script'
<insert Python code to start other Python script>
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
-
thanks. this is what i looking for. how to make it running background so that can listen from port at any time. – hddman Dec 21 '14 at 9:03
-
@hddman see cyberciti.biz/faq/linux-command-line-run-in-background – thekiwi5000 Dec 21 '14 at 13:58
-
had to be bind rather than connect! – user32697 Jul 11 '15 at 1:14