I have a python script given below which listens to a port. In this case, it is 4995. I need it to be always running and listen for connections and save the received data in a file.
import socket
import threading
from datetime import datetime
import time
class Testing:
def __init__(self):
self.PORT = 4995
self.SERVER = ''
self.ADDR = (self.SERVER, self.PORT)
self.count = 0
def handle_client(self, conn, addr):
print(f'[{datetime.now().strftime("%H:%M")}][NEW CONNECTION] {addr} connected.')
s = time.time()
while True:
if time.time() - s > 300:
conn.close()
print(f'[{datetime.now().strftime("%H:%M")}][CLOSE CONNECTION] {addr} closed.')
break
try:
msg = conn.recv(2048).decode('utf-8')
except ConnectionResetError:
print(f'[{datetime.now().strftime("%H:%M")}][CLOSE CONNECTION] {addr} closed by peers.')
break
else:
if msg:
print(f'[{datetime.now().strftime("%H:%M")}] {msg}')
with open('msg.txt','a') as file:
file.write(msg)
s = time.time()
# conn.close()
def start(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind(self.ADDR)
self.server.listen()
print(f'[LISTENING] Server is listening on {self.SERVER}:{self.PORT}')
while True:
try:
self.conn, addr = self.server.accept()
except OSError:
return
thread = threading.Thread(target=self.handle_client, args=(self.conn, addr))
thread.start()
print(f'[{datetime.now().strftime("%H:%M")}][ACTIVE CONNECTIONS] {threading.active_count() - 1}')
if __name__ == '__main__':
Testing().start()
I have tried running the above script like
nohup python3 -u script.py &
And it did work, but after some time, automatically client failed to establish a connection with the server, but the script was running fine. After some research, I found that nohup is not the right way to run my script because it kind of stops the script according to the available resources on Linux machine.
I want my script always to be running and listening for connections.