python - 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")
解决方案
每个服务器都应该在其单独的线程中运行,如下所示:
# ... 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
推荐阅读
- flutter - 将类从无状态转换为有状态后,更新控制器中的文本不起作用
- linux - 使用unix在每行末尾添加管道分隔符
- python - 如何将值添加到python中的dic内的列表中
- tabs - 如何自定义 Material UI Tab 的指示器宽度和位置
- python - “字典”对象没有属性“加载”错误
- node.js - Prisma js 返回连接字段
- python - Google 数据流模板 | Python SDK | 限制
- jquery - 在点击事件上停止 MutationOberserver
- javascript - 如何从 HTML 标签自动调用函数?
- java - 在 Java 中使用 Jackson 处理 JSON(反)序列化中的原始联合类型