import random import threading import socket import logging from systemd.journal import JournalHandler # Logging log = logging.getLogger(__name__) log.addHandler(JournalHandler()) class LocalServer(threading.Thread): def __init__(self, datastore): threading.Thread.__init__(self) self.datastore = datastore self.pleaseStop = False def run(self): sockfd = socket.socket() log.info("Socket successfully created") port = 12346 # Reserve a port on your computer...in our case it is 12345, but it can be anything sockfd.bind(('127.0.0.1', port)) log.info("Socket binded to %s" %(port)) sockfd.listen(5) # Put the socket into listening mode log.info("Socket is listening") while not self.pleaseStop: client, addr = sockfd.accept() # Establish connection with client log.debug('Got connection from', addr) rcvStr = client.recv(1024).decode() log.debug(rcvStr) if rcvStr != '': self.datastore.push(rcvStr) client.send(b'') # Send a message to the client client.close() log.debug("Socket is listening") log.info("Socket is closed\nExiting")