首页 > 解决方案 > How do i check for two connections to a sockets at once in python

问题描述

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")


标签: pythonwebserverconnectionport

解决方案


每个服务器都应该在其单独的线程中运行,如下所示:

# ... 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()

这里每个线程都有它的 while True 循环来接受多个连接,绑定和监听一个端口应该只发生一次。

其他选项是生成两个进程而不是两个线程,但这取决于您的用例,例如,如果您不需要在这些线程之间共享数据并且想要GIL的解决方法。在这种情况下,可能想看看https://docs.python.org/3/library/multiprocessing.html


推荐阅读