发送一些数据包后脚本中断功能 [英] Script breaks out of function after sending a few packets

查看:68
本文介绍了发送一些数据包后脚本中断功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Python程序,该程序在指定的时间内发送数据包.

I am writing a python program that sends packets for a specified amount of time.

发送脚本:

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秒钟,然后中断该功能并完成"操作.永远不会被打印.

I am expecting the sending script to run for the full 15 seconds and "done" to be printed. However, the sending script sends packets for approximately 2 seconds and then breaks out of the function and "done" never gets printed.

推荐答案

ray.remote 是非阻塞操作.发生的情况是您的程序开始远程函数调用,然后结束.完成后,它会撕裂射线束并结束远程功能.

ray.remote is a non-blocking operation. What's happening is your program is beginning the remote function call, then finishing. When it finishes, it tears down the ray cluster and ends the remote function.

您应该添加

s = send_message.remote()
ray.get(s)

ray.get 将尝试获取 send_message 的返回值(并返回),这意味着程序将不得不等待远程函数完成

The ray.get will try to get the return value of send_message (and return it), which means the program will have to wait for the remote function to finish.

这篇关于发送一些数据包后脚本中断功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆