2013-06-11 57 views
0

我试图播放一些数据并使用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

难道你不得不告诉你在哪里听的插座吗? –

+0

你可能想看看http://docs.python.org/2/library/socketserver.html,它很好地覆盖了这个应用程序与一个非常薄的糖层。 – synthesizerpatel

回答

1

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

添加一个循环,你的线程停止问题

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 
+0

在我的Mac上,它可以开启和关闭。 netcat不起作用。 – prosseek

2

有在代码中的三个问题。

  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 
+0

你打败了我。 – brice