python - 服务器的非阻塞套接字

标签 python sockets multiprocessing nonblocking

我在 stackoverflow.com 上检查了几个类似的线程,我想我可能需要为我的服务器脚本打开非阻塞套接字。因为,我不确定这是解决方案问题的标题可能是错误的。让我解释一下我的问题。

服务器应用程序等待连接,一旦客户端连接,它将询问服务器 ID,之后客户端将询问服务器配置,然后客户端将向服务器发送命令以开始测量传输。这是我的代码的简化版本:

def conn_handler(self, connection, address):
    self.logger.info("[%d] - Connection from %s:%d", 10, address[0], address[1])

    sending_measurements_enabled = False
    try:
        while True:
            data = connection.recv(2048)

            if data:
                command = get_command_from_data(data)
            else:
                command = None

            if command == 'start':
                sending_measurements_enabled = True
            elif command == 'stop':
                break
            elif command == 'id':
                connection.sendall(self.id)
            elif command == 'cfg':
                connection.sendall(self.cfg)

            if sending_measurements_enabled:
                connection.sendall(measurement)

    except Exception as e:
       print(e)
    finally:
        connection.close()
        print("Connection closed")

这是客户端脚本:
try:

    sock.sendall(get_id_command)    

    data = sock.recv(2048) # Do I need to wait for response?
    print(data)

    sock.sendall(get_conf_command)

    data = sock.recv(2048)
    print(data)

    sock.sendall(start_sending_measurements)
    data = sock.recv(2048)
    print(data)

    while True:
        sock.sendall(bytes('I do not want this', 'utf-8')) # I would like to keep receiving measurements without this
        data = sock.recv(2048)
        print(data)

finally:
    print('Closing socket...')
    sock.close()

这是我的问题:

当我运行客户端并发送命令以获取 ID 服务器将返回 ID 消息,然后客户端将发送命令以获取配置,服务器将返回配置消息但是当我发送 start命令服务器将只发送一个测量值,我猜connection.recv(2048)将阻止执行,直到服务器收到另一个命令。因此,我在 while True: 中添加了该行客户端脚本中的循环将继续发送(不必要的,无效的)命令,服务器将继续发送测量值。

如何在不一直从客户端发送命令的情况下解决这个问题。我希望能够只发送一个命令 start服务器将继续发送测量值,并且仅在客户端发送 stop 时停止命令。
此外,如果服务器收到 idcfg命令在发送测量值时首先发送idcfg而不是继续发送测量值。

最佳答案

在服务器循环调用 select.select([connection], [connection], [connection]) (select 模块提供了更多的功能,所以选择你喜欢的)。如果套接字是可读的,则读取命令并对其使用react。如果套接字是可写的(并且有数据请求),则发送测量值。

关于python - 服务器的非阻塞套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137680/

相关文章:

python - 使用 C 扩展 python 时查找内存泄漏

python - 有没有办法在 python 中访问嵌套或重新引发的异常?

java - 如何使用 Java 中的套接字处理来自 Teltonika GPS 设备的数据

c - 使用后如何正确删除信号量?

python - 将 pyqtgraph 多处理实现到 pyqt 小部件中

python - 将 Python 字典与包含的浮点值进行比较

python - countvectorizer 是否与 use_idf=false 的 tfidfvectorizer 相同?

c++ - 调用 QSslSocket::startServerEncryption,但没有任何反应

.net - 如何避免引发 AddressAlreadyInUseException?

c++ - 是否存在与平台无关的C++ fork 过程(例如某些标准库)?如何使我的代码可移植?