[英]Python sockets not receiving message
我正在嘗試使用帶套接字的python模擬令牌環,但是遇到了問題
主程序
node1 = node.node(8081,8082,token)
node2 = node.node(8082,8083,emptyFrame)
node3 = node.node(8083,8084,emptyFrame)
node4 = node.node(8084,8081,emptyFrame)
node1.firstrun()
node1.start()
node2.start()
node3.start()
node4.start()
節點
class node(threading.Thread):
def __init__(self,s,d,frame):
threading.Thread.__init__(self)
self.dest = d
self.current = frame
self.newframe = frame
self.source = s
def firstrun(self):
time.sleep(1)
host = "localhost"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", self.source))
sendmessage = str(self.newframe.fullFrame())
s.sendto(sendmessage, (host,self.dest))
print "sent"
def run(self):
host = "localhost"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", self.source))
while True:
print "running"
message, addr = s.recvfrom(4096)
self.newframe = message
print "received"
在代碼中,我創建了4個節點,為它們提供了不同的端口,其中一個消息。 我使第一個端口向下一個節點發送消息,並且所有這些都運行main函數。 在主要功能中,我等待消息並執行while循環。 將為所有4個節點打印運行,但不會收到。 因此,我不明白為什么節點從未收到第一個令牌。 我的程序無限等待。 (為了清楚起見,我刪除了多余的代碼,它們都不會阻礙主套接字進程)
您應該首先分派所有線程,否則不進行套接字監聽。 time.sleep()是糟糕的編碼風格,涉及線程時,您不能依賴定時函數。
分派線程。
threads = [node1, node2, node3, node4]
[thread.start() for thread in threads]
和刮firstrun()
從節點類的方法,要么在實現它class initnode
(它不需要是threading.Thread的孩子)或只是從你的主發送關閉消息,你派出你的插座線后 。
您可以將順序更改為:
node1.start()
node2.start()
node3.start()
node4.start()
node1.firstrun()
node2.firstrun()
node3.firstrun()
node4.firstrun()
然后,您將看到打印“已接收”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.