1 ## Copyright 2002 Andrew Loewenstern, All Rights Reserved
5 # simple UDP communicator
8 def __init__(self, host, port):
10 self.sock = socket(AF_INET, SOCK_DGRAM)
11 self.sock.setblocking(0)
12 self.sock.bind((host, port))
14 def qMsg(self, msg, host, port):
15 self.msgq.append((msg, host, port))
20 def dispatchMsg(self):
22 msg, host, port = self.msgq[0]
24 self.sock.sendto(msg, 0, (host, port))
29 msg = self.sock.recvfrom(65536)
31 if tup[1] == "Resource temporarily unavailable":
43 ###########################
46 class ListenerTest(unittest.TestCase):
48 self.a = Listener('localhost', 8080)
49 self.b = Listener('localhost', 8081)
55 assert self.a.qLen() == 0, "expected queue to be empty"
56 self.a.qMsg('hello', 'localhost', 8081)
57 assert self.a.qLen() == 1, "expected one message to be in queue"
58 self.a.qMsg('hello', 'localhost', 8081)
59 assert self.a.qLen() == 2, "expected two messages to be in queue"
61 assert self.a.qLen() == 1, "expected one message to be in queue"
63 assert self.a.qLen() == 0, "expected all messages to be flushed from queue"
65 def testSendReceiveOne(self):
66 self.a.qMsg('hello', 'localhost', 8081)
69 assert self.b.receiveMsg()[0] == "hello", "did not receive expected message"
70 assert self.b.receiveMsg() == (), "received unexpected message"
72 self.b.qMsg('hello', 'localhost', 8080)
75 assert self.a.receiveMsg()[0] == "hello", "did not receive expected message"
77 assert self.a.receiveMsg() == (), "received unexpected message"
79 def testSendReceiveInterleaved(self):
80 self.a.qMsg('hello', 'localhost', 8081)
81 self.a.qMsg('hello', 'localhost', 8081)
85 assert self.b.receiveMsg()[0] == "hello", "did not receive expected message"
86 assert self.b.receiveMsg()[0] == "hello", "did not receive expected message"
87 assert self.b.receiveMsg() == (), "received unexpected message"
89 self.b.qMsg('hello', 'localhost', 8080)
90 self.b.qMsg('hello', 'localhost', 8080)
94 assert self.a.receiveMsg()[0] == "hello", "did not receive expected message"
95 assert self.a.receiveMsg()[0] == "hello", "did not receive expected message"
96 assert self.a.receiveMsg() == (), "received unexpected message"
99 if __name__ == '__main__':