hey there i have written a code that makes a tcp connection with a outside device. my server program collects the in coming data reads it a stores to file. the problem is that i am using the listen command and if i force a shut down i have to change ports. is there any way to make the program exit after it closes the port so i can run again and keep the same port. would like to know cuz i will be talking with a micro controller over network and its a pain to reprogram the port on it. here is my code.
#!/usr/bin/python
import sys
import optparse
import time
import socket
def timestamp():
lt = time.localtime( time.time())
return "%02d_%02d_ %04d " % (lt[1], lt[2], lt[0])
checktime=times tamp()
HOST = ''
PORT = 6005
while 1:
try :
s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
except (KeyboardInterr upt, SystemExit) :
conn.close()
while 1:
dataIn = conn.recv(1024)
data = checktime + "" + dataIn
time = data[0:10]
station = data[11:20]
tag = data[22:30]
print(time)
print(station)
print(tag)
timefile='C:/Users/Chris/Desktop/Project/TimeFiles/' + time + '.txt'
f=open(timefile ,'a')
f.write(data + '\r\n')
f.close()
stationfile='C:/Users/Chris/Desktop/Project/StationFiles/' + station + '.txt'
g=open(stationf ile,'a')
g.write(data + '\r\n')
g.close()
tagfile='C:/Users/Chris/Desktop/Project/TagFiles/' + tag + '.txt'
s=open(tagfile, 'a')
s.write(data + '\r\n')
s.close()
break
conn.close()
#!/usr/bin/python
import sys
import optparse
import time
import socket
def timestamp():
lt = time.localtime( time.time())
return "%02d_%02d_ %04d " % (lt[1], lt[2], lt[0])
checktime=times tamp()
HOST = ''
PORT = 6005
while 1:
try :
s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
except (KeyboardInterr upt, SystemExit) :
conn.close()
while 1:
dataIn = conn.recv(1024)
data = checktime + "" + dataIn
time = data[0:10]
station = data[11:20]
tag = data[22:30]
print(time)
print(station)
print(tag)
timefile='C:/Users/Chris/Desktop/Project/TimeFiles/' + time + '.txt'
f=open(timefile ,'a')
f.write(data + '\r\n')
f.close()
stationfile='C:/Users/Chris/Desktop/Project/StationFiles/' + station + '.txt'
g=open(stationf ile,'a')
g.write(data + '\r\n')
g.close()
tagfile='C:/Users/Chris/Desktop/Project/TagFiles/' + tag + '.txt'
s=open(tagfile, 'a')
s.write(data + '\r\n')
s.close()
break
conn.close()