我在 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
时停止命令。此外,如果服务器收到
id
或 cfg
命令在发送测量值时首先发送id
或 cfg
而不是继续发送测量值。
最佳答案
在服务器循环调用 select.select([connection], [connection], [connection])
(select 模块提供了更多的功能,所以选择你喜欢的)。如果套接字是可读的,则读取命令并对其使用react。如果套接字是可写的(并且有数据请求),则发送测量值。
关于python - 服务器的非阻塞套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137680/