簡體   English   中英

使用Python廣播和接收數據

[英]Broadcasting and receiving data with Python

我正在嘗試廣播一些數據並使用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)處永遠等待。 可能是什么問題?

代碼中存在三個問題。

  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

您的線程可能會開始偵聽之前發送其數據。

在線程中添加循環以解決問題

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM