如何解决发送一些数据包后脚本中断功能
我正在编写一个Python程序,该程序在指定的时间内发送数据包。
发送脚本:
import socket
import time
import networkparam
import ray
ray.init()
transformer_sending_time = 0
final_message_sent = False
@ray.remote
def send_message():
"""
Sends an abnormal measurement to the specified ip address or port number given by the networkparam module
Parameters
----------
None,however we can consider the definitions in networkparam as the function args
Returns
----------
None
"""
global transformer_sending_time
global final_message_sent
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip = networkparam.ip
port = networkparam.controller_port
message = b"bait"
seconds = 15
end_time = time.time() + seconds
while time.time() < end_time:
sock.sendto(message,(ip,port))
transformer_sending_time = time.time()
print("done")
final_message_sent = True
s = send_message.remote()
接收脚本:
import time
import socket
import networkparam
ip = networkparam.ip
controller_port = networkparam.controller_port
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((ip,controller_port))
while True:
data,addr = sock.recvfrom(1024)
if not data:
break
print("received message: %s" % data)
我希望发送脚本运行整整15秒钟,并且“完成”将被打印。但是,发送脚本发送数据包大约2秒钟,然后中断该功能,并且“完成”永远不会被打印。
解决方法
ray.remote
是非阻塞操作。发生的情况是您的程序正在开始远程函数调用,然后结束。完成后,它会撕裂射线束并结束远程功能。
您应该添加
s = send_message.remote()
ray.get(s)
ray.get
将尝试获取send_message
的返回值(并返回它),这意味着程序将不得不等待远程函数完成。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。