【问题标题】:Broadcasting and receiving data with Python使用 Python 广播和接收数据
【发布时间】:2013-06-21 09:00:54
【问题描述】:

我正在尝试广播一些数据并使用 python 接收它。 这是我想出的代码。

from socket import *
import threading

class PingerThread (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run (self):
        print 'start thread'
        cs = socket(AF_INET, SOCK_DGRAM)
        cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        cs.sendto('This is a test', ('192.168.65.255', 4499))

a = PingerThread() 
a.start()

cs = socket(AF_INET, SOCK_DGRAM)
data = cs.recvfrom(1024) # <-- waiting forever

但是,代码似乎永远在 cs.recvfrom(1024) 等待。可能有什么问题?

【问题讨论】:

标签: python networking udp


【解决方案1】:

代码中存在三个问题。

  1. 监听器没有绑定任何东西。
  2. 打开的套接字没有关闭。
  3. 有时,线程生成得太快以至于侦听器错过了广播数据。

这是修改后的工作代码。

from socket import *
import time
import threading

port = 4490
class PingerThread (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run (self):
        print 'start thread'
        cs = socket(AF_INET, SOCK_DGRAM)
        cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

        time.sleep(0.1) # issue 3 solved
        cs.sendto('This is a test', ('192.168.65.255', port))

a = PingerThread()
a.start()

cs = socket(AF_INET, SOCK_DGRAM)
try:
    cs.bind(('192.168.65.255', port)) # issue 1 solved
except:
    print 'failed to bind'
    cs.close()
    raise
    cs.blocking(0)

data = cs.recvfrom(20)  
print data
cs.close() # issue 2 solved

【讨论】:

    【解决方案2】:

    您的线程可能会在您开始收听之前发送其数据。

    在你的线程中添加一个循环来停止问题

    from socket import *
    import threading
    import time
    
    class PingerThread (threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
    
        def run (self):
            for i in range(10):
              print 'start thread'
              cs = socket(AF_INET, SOCK_DGRAM)
              cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
              cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
              cs.sendto('This is a test', ('192.168.1.3', 4499))
              time.sleep(1)
    
    a = PingerThread() 
    a.start()
    
    
    cs = socket(AF_INET, SOCK_DGRAM)
    try:
        cs.bind(('192.168.1.3', 4499))
    except:
        print 'failed to bind'
        cs.close()
        raise
        cs.blocking(0)
    data = cs.recvfrom(1024) # <-- waiting forever
    print data
    

    【讨论】:

      猜你喜欢
      • 2014-05-17
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2016-11-01
      • 2017-10-16
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多