简体   繁体   English

检查是否有任何套接字连接正在等待(python)

[英]Check if any socket connections are waiting (python)

I am trying to run a task in an infinite loop but I would like to reserve the opportunity of changing some parameters along the way, hence I thought of using sockets to get this data over to my code.我试图在无限循环中运行任务,但我想保留在此过程中更改某些参数的机会,因此我想到使用套接字将这些数据传递给我的代码。 Unfortunately reading from a file is likely to be too slow.不幸的是,从文件中读取可能太慢了。

The problem is that in most cases there are no incoming connections and I do not want to block the code.问题是在大多数情况下没有传入连接,我不想阻止代码。 The best thing I could come up with is setblocking(False) and a try block but I wonder if someone can do this in a more pythonic way.我能想到的最好的办法是setblocking(False)和一个try块,但我想知道是否有人可以用更 Python 的方式做到这一点。

Sorry if this is super trivial.对不起,如果这是非常微不足道的。 I am new to networking.我是网络新手。

A short example of the thing I would like:我想要的东西的一个简短例子:

import socket
from time import sleep

HOST = '127.0.0.1'
PORT = 62800 

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
server.setblocking(False)
server.bind((HOST, PORT))
server.listen()

a_parameter = 0.1
counter = 0

def task(a):
    sleep(a)

    global counter
    counter+=1
    print(counter)


while True:
    try:
        conn, addr = server.accept() # will throw an error if no connections are in the queue
        with conn:
            print('Connected by', addr)
            data = conn.recv(1024)  
            a_parameter = float(data.decode("utf-8"))
            print("New parameter:", a_parameter)
    except:
        pass

    task(a_parameter)

You can try it with this client:你可以试试这个客户端:


import socket
import sys

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 62800        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(bytes(sys.argv[1], 'utf-8'))

In the end I opted for a separate thread based on a comment from user207421 as it feels less wasteful than try and more simple than asyncio .最后,我根据 user207421 的评论选择了一个单独的线程,因为它比try浪费更少,而且比asyncio更简单。 I copy my code here in case anyone is interested in the future:我在这里复制我的代码,以防有人对未来感兴趣:

from threading import Thread
import socket
from time import sleep

HOST = '127.0.0.1'
PORT = 62800 


a_parameter = 0.1
counter = 0

def socket_handler_thread_function(threadname):

    global a_parameter

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    server.bind((HOST, PORT))
    server.listen()

    print('listening on', (HOST, PORT))

    while True:
        conn, addr = server.accept()
        with conn:
            print('Connected by', addr)
            data = conn.recv(1024)  
            a_parameter = float(data.decode("utf-8"))
            print("New parameter:", a_parameter)


def task(a):
    sleep(a)

    global counter
    counter+=1
    print(counter)

# daemon mode terminates the thread when the main code is killed 
socket_handler_thread = Thread(
        target=socket_handler_thread_function, 
        args=(1, ), 
        daemon=True
    )
socket_handler_thread.start()

while True:
    task(a_parameter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM