I'm running a python script that listens for incoming connections to my computer. I'm listening on two ports 9999 and 9998. however when im checking for connections to my first port by using .accept() it then waits until i have a connection to run the code underneath meaning my other port can check for connections.
I want to be able to check for connections simultaneously and run code according to what port has been connected to, this is my current code.
import socket
import subprocess
import os
while 1 > 0:
# Set connection for C_shutdown script on port 9999
HOST = '192.168.1.46'
PORT = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
print("Listening for Shutdown connection")
# Set connection for Light_on script on port 9998
HOST = '192.168.1.46'
PORT2 = 9998
light_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
light_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
light_socket.bind((HOST, PORT2))
light_socket.listen(10)
print("Listening for Light Connection")
l = light_socket.accept()
print("Light script connected")
s = server_socket.accept()
print("Shutdown Script Connected")
Each server should be running in its separate thread, something like this:
# ... other imports ...
import threading
def server_job():
# ... Code for server_socket ...
print("Listening for server connection")
while True:
s = server_socket.accept()
# ... Anything you want to do with s ...
def light_job():
# ... Code for light_socket ...
print("Listening for Light Connection")
while True:
l = light_socket.accept()
# ... Anything you want to do with l ...
# Creates Thread instances that will run both server_job and light_job
t_server = threading.Thread(target=server_job)
t_light = threading.Thread(target=light_job)
# Begin their execution
t_server.start()
t_light.start()
# Wait for both threads to finish their execution
t_light.join()
t_server.join()
Here each thread has its while True loop to accept several connections, the binding and listening to a port should happen only once.
Other option would be spawning two processes instead of two threads, but that depends on your use case, for example if you don't require to share data between those threads and want a workaround for GIL. In that case, might want to take a look at https://docs.python.org/3/library/multiprocessing.html