isengard-bot/localServer.py

41 lines
1.2 KiB
Python
Raw Normal View History

2022-02-05 00:46:57 +01:00
import random
import threading
import socket
2022-02-08 15:46:17 +01:00
import logging
from systemd.journal import JournalHandler
# Logging
log = logging.getLogger(__name__)
log.addHandler(JournalHandler())
2022-02-05 00:46:57 +01:00
class LocalServer(threading.Thread):
2023-03-15 19:41:29 +01:00
def __init__(self, datastore):
2022-02-05 00:46:57 +01:00
threading.Thread.__init__(self)
2023-03-15 19:41:29 +01:00
self.datastore = datastore
2022-02-07 18:39:34 +01:00
self.pleaseStop = False
2022-02-08 15:46:17 +01:00
2022-02-05 00:46:57 +01:00
def run(self):
2022-02-08 15:46:17 +01:00
sockfd = socket.socket()
2022-02-08 20:25:51 +01:00
log.info("Socket successfully created")
2022-02-06 01:29:59 +01:00
port = 12346 # Reserve a port on your computer...in our case it is 12345, but it can be anything
2022-02-08 15:46:17 +01:00
sockfd.bind(('127.0.0.1', port))
2022-02-08 20:25:51 +01:00
log.info("Socket binded to %s" %(port))
2022-02-05 00:46:57 +01:00
sockfd.listen(5) # Put the socket into listening mode
2022-02-08 20:25:51 +01:00
log.info("Socket is listening")
2022-02-05 00:46:57 +01:00
2022-02-07 18:39:34 +01:00
while not self.pleaseStop:
2022-02-05 00:46:57 +01:00
client, addr = sockfd.accept() # Establish connection with client
2022-02-08 20:25:51 +01:00
log.debug('Got connection from', addr)
2022-02-05 00:46:57 +01:00
rcvStr = client.recv(1024).decode()
2022-02-08 20:25:51 +01:00
log.debug(rcvStr)
2022-02-08 15:46:17 +01:00
2022-02-07 18:39:34 +01:00
if rcvStr != '':
2023-03-15 19:41:29 +01:00
self.datastore.push(rcvStr)
2022-02-08 15:46:17 +01:00
2022-02-05 00:46:57 +01:00
client.send(b'') # Send a message to the client
client.close()
2022-02-08 20:25:51 +01:00
log.debug("Socket is listening")
log.info("Socket is closed\nExiting")