By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,715 Members | 748 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,715 IT Pros & Developers. It's quick & easy.

stopping .listen command

P: 2
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=timestamp()
HOST = ''
PORT = 6005

while 1:
try :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)

conn, addr = s.accept()
except (KeyboardInterrupt, 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(stationfile,'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()
Feb 17 '11 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.