简体   繁体   English

Python套接字未收到消息

[英]Python sockets not receiving message

I'm trying to simulate a token ring using python with sockets, but I have run into a problem 我正在尝试使用带套接字的python模拟令牌环,但是遇到了问题

main program 主程序

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()

node 节点

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"

In the code, I create 4 nodes giving them different ports and one of them a message. 在代码中,我创建了4个节点,为它们提供了不同的端口,其中一个消息。 I make this first port send a message to the next node and all of them run the main function. 我使第一个端口向下一个节点发送消息,并且所有这些都运行main函数。 In the main function I wait for a message and do a while loop. 在主要功能中,我等待消息并执行while循环。 The runing gets printed for all 4 nodes but the received does not. 将为所有4个节点打印运行,但不会收到。 Thus I don't understand why the node never receives the first token. 因此,我不明白为什么节点从未收到第一个令牌。 My program just waits infinitely. 我的程序无限等待。 (I removed excess code for clarity, none of it should have hindered the main socket process) (为了清楚起见,我删除了多余的代码,它们都不会阻碍主套接字进程)

you should first dispatch all the threads, otherwise there is no socket listening. 您应该首先分派所有线程,否则不进行套接字监听。 time.sleep() is bad coding style, you can't rely on timed functions when it comes to threading. time.sleep()是糟糕的编码风格,涉及线程时,您不能依赖定时函数。

dispatch your threads at one point. 分派线程。

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

and scrape the firstrun() method from your node class and either implement it in a class initnode (it doesn't need to be a child of threading.Thread) or just send off the message from your main after you dispatched your socket threads. 和刮firstrun()从节点类的方法,要么在实现它class initnode (它不需要是threading.Thread的孩子)或只是从你的主发送关闭消息,你派出你的插座线

You may change the sequence to: 您可以将顺序更改为:

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

Then you will see "received" be printed. 然后,您将看到打印“已接收”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM