From dc088179f5ef19c66b3d621fae618e98e7b70920 Mon Sep 17 00:00:00 2001 From: berhsi Date: Fri, 26 Jul 2019 19:43:59 +0200 Subject: [PATCH] initiler commit initialer commit eines servers, der ein bit aus einem socket liest --- server-clear.py | 75 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100755 server-clear.py diff --git a/server-clear.py b/server-clear.py new file mode 100755 index 0000000..4fa1712 --- /dev/null +++ b/server-clear.py @@ -0,0 +1,75 @@ +#!/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() + 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])) + 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()