#!/usr/bin/env python

import socket
from time import time, gmtime, strftime


TCP_IP = '192.168.178.5'
#TCP_IP = '195.160.169.47'
TCP_PORT = 5005
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.settimeout(None)
s.listen(1)

while 1:
	print ""
	conn, addr = s.accept() #one connection for every reading cycle
	conn.settimeout(15.0) #sould be higher than softtimeout with connecion close of nodes
	timestamp=time()
	timestamp_int=int(timestamp)
	filename=strftime("%Y%j", gmtime())+".txt"
	print 'Connection address:', addr
	print "Timestamp:"+str(timestamp)
	print "Filename="+filename

	dataline=""+str(timestamp_int)
	try:
		while 1:
		    data = conn.recv(BUFFER_SIZE)
		    if not data: break
		    #print "received data:", data
		    dataline=dataline+""+data
		    print data
		    #conn.send(data)  # echo

		print dataline
	
		with open(filename, "a") as f:
			f.write(dataline+"\n")



	except socket.timeout:
		print "->Connection timed out!"

	conn.close()
