Python套接字没有收到消息

时间:2012-02-20 00:29:16

标签: python multithreading sockets

我正在尝试使用带有套接字的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函数。在main函数中,我等待消息并执行while循环。所有4个节点都会打印运行,但收到​​的不是。因此,我不明白为什么节点永远不会收到第一个令牌。我的程序无限期等待。 (为清楚起见,我删除了多余的代码,没有一个代码阻止主套接字进程)

2 个答案:

答案 0 :(得分:1)

你应该首先调度所有线程,否则没有套接字监听。 time.sleep()是错误的编码风格,在线程化方面你不能依赖定时函数。

一次调度你的线程。

threads = [node1, node2, node3, node4]
[thread.start() for thread in threads]

并从您的节点类中删除firstrun()方法,并在class initnode中实现它(它不需要是threading.Thread的子节点)或者只是从您的节点发送消息主 之后发送了套接字线程。

答案 1 :(得分:0)

您可以将序列更改为:

node1.start()
node2.start()
node3.start()
node4.start()
node1.firstrun()
node2.firstrun()
node3.firstrun()
node4.firstrun()

然后你会看到“已收到”。

相关问题