【问题标题】:Python sockets and end loopPython套接字和结束循环
【发布时间】:2021-08-12 15:09:08
【问题描述】:

我正在开发一个使用套接字进行通信的项目。我想要的是创建一个连续发送数据的循环,但是当我发送消息 'stop' 时,需要停止循环。我有一个问题,当循环开始时,没有收到新消息。

我的表单上有 2 个按钮。开始和停止。首先我单击按钮 1 并开始循环,但是当单击按钮时,什么也没有发生。

基本上是我写的代码。我在电脑上没有以太网,所以我在手机上写字。对不起。

蟒蛇

def loop:
     while stus:
             socket.sendall(data) 
#in main
stus = True
while true:
         str = socket.recv(1024)
         if str == "startloop":
               loop()
         elif str = "stoploop"
                 stus=False
                   

c#

//But1
socket.send("startloop") 

//But2
socket.send("stoploop")

【问题讨论】:

    标签: python c# loops sockets


    【解决方案1】:

    “startloop”消息将您的代码发送到loop(),它一直运行到无穷大。因此,应用程序永远不会读取“stoploop”消息。如果您希望您的代码同时做两件事(继续发送数据 + 检查停止消息),那么您必须:

    1. 启动后台线程以继续发送数据,并确保在收到停止循环时退出该线程。
    2. 将 socket.sendall 移动到主 while 循环中,使您的套接字调用非阻塞(参见docs),然后如果 socket.recv 引发 socket.timeout(因为没有数据),您可以调用 socket.sendall

    选项 2 看起来像这样;

    socket.setnonblocking()
    started = False
    while True:
      try:
        message = socket.recv(1024)
      except socket.timeout:
        if started:
          socket.sendall(data)
      else:
        if message == 'startloop':
          started = True
        if message == 'stoploop':
          break
    

    但您可能需要考虑设置超时以避免 100% 的 CPU 使用率。

    【讨论】:

      【解决方案2】:

      我认为问题在于变量的名称。 str 是关键字,str == startloopstr == stoploop 的输出将始终为 False,因为 str 类不等于字符串 startloop。 尝试更改名称,例如str_test

      如果您想分别停止或继续执行,请确保使用breakcontinue

      def loop():
               while stus:
                       socket.sendall(data) 
      #in main
      while true:
           str_test = socket.recv(1024)
           if str_test == "startloop":
               loop()
           elif str_test = "stoploop"
               break
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-18
        • 2015-06-30
        • 1970-01-01
        • 2018-07-13
        • 2017-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多