我在模拟一个简化的无线网络,我想用一个线程和一个发送和接收的套接字来表示每个节点,问题是当我做了两个线程的示例时,第一条消息没有收到
我试着测试第一个线程是否正在使用另一个接收器发送并且它正在工作,然后试着测试第二个线程接收器是否正在工作并且它正在工作
import socket
import time
import threading
import struct
import sys
class PingerThread(threading.Thread):
def __init__(self, node):
threading.Thread.__init__(self)
self.node = node
def run(self):
print('start thread', self.node)
multicast_group = '224.3.29.71' # for listner
server_address = ('', 10000)
# Create the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(server_address)
# Tell the operating system to add the socket to the multicast group
# on all interfaces.
group = socket.inet_aton(multicast_group)
mreq = struct.pack('4sL', group, socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
# Receive loop
# begin as listner
while True:
msg1= '\n node' + str(self.node) + ' waiting to receive message'
print(msg1)
x = self.node
sock.settimeout(x)
try:
data, address = sock.recvfrom(1024)
except socket.timeout:
break;
if ((data.decode('utf-8'))[0] != str(self.node)):
msg2 = '\n!node' + str(self.node) + 'received: ' + data.decode('utf-8')
print(msg2)
# transform to sender
message = str(self.node) + ' first msg'
msg3 = '\nsending node' + message
print(msg3)
multicast_group = ('224.3.29.71', 10000) # pour sender
sock.sendto(message.encode(), multicast_group)
# back to listner
sock.settimeout(None)
printing = True #boolean to control print function
while True:
if printing == True:
msg4 = '\n node' + str(self.node) + ' waiting to receive message'
print(msg4)
printage = False
sock.settimeout(None)
try:
data, address = sock.recvfrom(1024)
except socket.timeout:
break;
if ((data.decode('utf-8'))[0] != str(self.node)):#only print msg if you are not the sender
msg5 = '\n!!!!node' + str(self.node) + ' received: ' +data.decode('utf-8')
printing = True
print(msg5)
a = PingerThread(8)
a.start()
b = PingerThread(2)
b.start()
目前没有回答
相关问题 更多 >
编程相关推荐