I’m trying to simulate a token ring using python with sockets, but I have run into a problem
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. I make this first port send a message to the next node and all of them run the main function. In the main function I wait for a message and do a while loop. The runing gets printed for all 4 nodes but the received does not. 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.
dispatch your threads at one point.
and scrape the
firstrun()method from your node class and either implement it in aclass 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.