#!/usr/bin/python3 # file: server-clear.py # date: 26.07.2019 # email: berhsi@web.de # server, who listen for connections for localhost, port 64000 and ipv4. import socket from time import time, ctime from sys import exit def connection_handle(conn): data = conn.recv(1).decode() if data == '0' or data == '1': if update_status(data) == True: conn.send(data.encode()) else: conn.send(b'3') else: print('Invalid argument') return False return True def update_status(data): try: print('Update status ...') if data == '0': status = 'false' else: status = 'true' lastchange = str(time()).split('.')[0] print('Change status: {}: {}'.format(lastchange, status)) except Exception as e: print('Error: {}'.format(e)) return False return True def main(): HOST = '127.0.0.1' PORT = 64000 with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as mySocket: print('Socket created') try: mySocket.bind((HOST, PORT)) mySocket.listen(5) print('Listen on {} at Port {}'.format(HOST, PORT)) except Exception as e: print('Error: unable to bind and listen') print('Error: {}'.format(e)) while True: conn = None try: conn, addr = mySocket.accept() print('Connection from {}:{}'.format(addr[0], addr[1])) conn.settimeout(3.0) connection_handle(conn) except KeyboardInterrupt: print('\b\bExit') exit() except Exception as e: print('Error: {}'.format(e)) finally: if conn: conn.close() if __name__ == '__main__': main()