I have built a simple TCP server, that runs on my Pi, that stores some data received from a GPRS module. It generally works fine, but at random intervals (some hours or even a couple of days) my python script doesn't receive any more data. I suspect that this is caused by a TCP connection that does not close properly. If I kill the script and try to run it again I get an error that the port is being used.
This is my code so far:
from socket import *
import time
HOST = ''
PORT = 24071
BUFFER_SIZE = 200
b=" "
data=" "
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
while 1:
s.listen(1)
print ''
print ''
print ''
mTime = time.strftime('%d-%m-%y %H:%M:%S')
print mTime
print 'Port',PORT,': listening...'
conn, addr = s.accept()
print 'Connection address:', addr, conn
while 1:
data = conn.recv(BUFFER_SIZE)
print "received:", data
if not data: break
if data=="start":
b=conn.recv(BUFFER_SIZE)
print "data:", b
if not b: break
if data=="check":
print "check!!"
conn.send("test")
I would like to end any persistent connections after some seconds (ex. 20s). Is there any way i could do this?