1 # Copyright (c) 2011 Nicira Networks
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
16 ovsudp contains listener and sender classes for UDP protocol
19 from twisted.internet.protocol import DatagramProtocol
20 from twisted.internet.task import LoopingCall
21 import array, struct, time
24 class UdpListener(DatagramProtocol):
26 Class that will listen for incoming UDP packets
31 def startProtocol(self):
32 print "Starting UDP listener"
34 def stopProtocol(self):
35 print "Stopping UDP listener"
37 def datagramReceived(self, data, (_1, _2)):
38 """This function is called each time datagram is received"""
40 self.stats.append(struct.unpack_from("Q", data, 0))
42 pass #ignore packets that are less than 8 bytes of size
45 """Returns number of packets that were actually received"""
46 return len(self.stats)
49 class UdpSender(DatagramProtocol):
51 Class that will send UDP packets to UDP Listener
53 def __init__(self, host, count, size, duration):
54 #LoopingCall does not know whether UDP socket is actually writable
58 self.duration = duration
59 self.start = time.time()
61 self.data = array.array('c', 'X' * size)
63 def startProtocol(self):
64 print "Starting UDP sender"
65 self.looper = LoopingCall(self.sendData)
66 period = self.duration / float(self.count)
67 self.looper.start(period , now = False)
69 def stopProtocol(self):
70 print "Stopping UDP sender"
71 if (self.looper is not None):
75 def datagramReceived(self, data, (host, port)):
79 """This function is called from LoopingCall"""
80 if self.start + self.duration < time.time():
85 struct.pack_into('Q', self.data, 0, self.sent)
86 self.transport.write(self.data, self.host)
89 """Returns number of packets that were sent"""