pro*_*eek 0 python networking udp
我正在尝试播放一些数据并使用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
Run Code Online (Sandbox Code Playgroud)
但是,代码似乎永远等待着cs.recvfrom(1024).可能有什么问题?
代码中有三个问题.
这是修改后的工作代码.
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4640 次 |
| 最近记录: |