I'm constructing a python server for some apps running on different computers in the house. To do this I'm trying to set up a server responding to commands from any of these apps. The socket comm works adequately, and Python indicates the command is executed, but there are no changes to variables I would expect to change.
I'm testing on Python 3.7.
import sys
import time
import socket
data = "";
result = "";
def server():
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
while 1:
data = conn.recv(BUFFER_SIZE).decode()
if (len(data)>0):
try:
exec(data);
print("Execution OK of "+data+", result: "+result);
conn.send(result.encode()) # send the final value back to the client
except Exception as e:
print("Error executing: ",data, " msg: ",str(e));
else:
time.sleep(1);
result = "UNINITIALIZED"
server()
To test this I issue the following commands from another python console:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "result='initialized'";
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE.encode())
data = s.recv(BUFFER_SIZE).decode()
s.close()
print("received data:", data)
I expect that after the server receives the data (which works fine), the value of "result" should change to "initialized", and I'd see the updated value in both the server, and in the reply echoed back to the client. In both cases "result" retains the original "UNINITIALIZED" value.
Thanks in advance!