doorstatus/server-clear.py
berhsi 0b91b007db client and server works with bytes and nr18.space now
both parts now uses byteorder, int.from_bytes() and data.to_bytes(). to compare values,
raw data are cast to integer. furthermore encode() is nowhere used. at the moment the server
listen at nr18.space at port 10001.
2019-07-27 00:44:53 +02:00

77 lines
1.9 KiB
Python
Executable file

#!/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, byteorder
def connection_handle(conn):
bom = byteorder
raw_data = conn.recv(1)
print('Data recived: {}'.format(raw_data))
data = int.from_bytes(raw_data, bom)
if data == 0 or data == 1:
if update_status(data) == True:
conn.send(data.to_bytes(1, bom))
else:
conn.send(b'\x03')
else:
print('Invalid argument')
conn.send(b'3')
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 = 'nr18.space'
PORT = 10001
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:
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))
if __name__ == '__main__':
main()