【问题标题】:Python sockets not receiving messagePython套接字未收到消息
【发布时间】:2012-02-20 00:29:16
【问题描述】:

我正在尝试使用带有套接字的 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 个节点,为它们提供不同的端口,其中一个提供消息。我让第一个端口向下一个节点发送一条消息,它们都运行主函数。在主函数中,我等待一条消息并执行一个 while 循环。为所有 4 个节点打印运行,但接收到的却没有。因此我不明白为什么节点永远不会收到第一个令牌。我的程序只是无限等待。 (为了清楚起见,我删除了多余的代码,它们都不应该妨碍主套接字进程)

【问题讨论】:

    标签: python multithreading sockets


    【解决方案1】:

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

    在某一时刻分派你的线程。

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

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

    【讨论】:

    • 谢谢,我没有注意到,node2 没有时间设置来接收来自 node1 的消息。 :)
    【解决方案2】:

    您可以将顺序更改为:

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

    然后你会看到“received”被打印出来。

    【讨论】:

    • 当我将 node1.firstrun() 放在要运行的初始方法的末尾时,我尝试了类似的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2012-01-05
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    相关资源
    最近更新 更多