47 lines
1.1 KiB
Python
47 lines
1.1 KiB
Python
import socket
|
|
import threading
|
|
import re
|
|
|
|
# protocolo
|
|
# operacion: valor + operando + valor\n
|
|
# OK:<resultado>\n
|
|
# ERROR:<mensaje>\n
|
|
|
|
def validate_pdu(pdu):
|
|
return re.match(r'\d+\s*[-+*/]\s*\d+', pdu) != None
|
|
|
|
def handle_connection(conn):
|
|
try:
|
|
r = conn.makefile('rw')
|
|
while True:
|
|
frame = r.readline()
|
|
pdu = frame.split()
|
|
command = ''.join(pdu)
|
|
|
|
print('got %s' % (frame))
|
|
if validate_pdu(command):
|
|
try:
|
|
r.writelines(["OK:%s\n" % (eval(command))])
|
|
except:
|
|
r.writelines(["ERR:exception\n"])
|
|
else:
|
|
r.writelines(["ERROR:😒yntax error\n"])
|
|
r.flush()
|
|
except:
|
|
pass
|
|
conn.close()
|
|
|
|
|
|
# MAIN
|
|
|
|
PORT=65517
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
s.bind(('', PORT))
|
|
s.listen(12)
|
|
while True:
|
|
conn, addr = s.accept()
|
|
print('Connected by', addr)
|
|
t = threading.Thread(target=handle_connection, args=(conn,))
|
|
t.start()
|