Skip to content

Instantly share code, notes, and snippets.

@ra1u

ra1u/client.py Secret

Created July 19, 2012 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ra1u/3144857 to your computer and use it in GitHub Desktop.
Save ra1u/3144857 to your computer and use it in GitHub Desktop.
updating 1000 udp servers
#!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet.protocol import DatagramProtocol,Factory
from twisted.internet import reactor
_nclients = 0
_client_gen = []
_spawn_counter = 0
class EchoClientDatagramProtocol(DatagramProtocol):
def __init__(self,datasource):
self.datasource = datasource
def startProtocol(self):
global _spawn_counter , _nclients
_spawn_counter +=1
self.transport.connect('127.0.0.1', 62010)
self.sendDatagram()
def sendDatagram(self):
try:
while 1:
datagram = next(self.datasource).strip()
if len(datagram) > 0:
break
self.transport.write(datagram)
except StopIteration:
spawn_more()
self.kill_one()
def datagramReceived(self, datagram, host):
s = str(datagram).strip()
if s == 'OK':
self.sendDatagram()
else:
print s
def stop(self):
self.transport.stopListening()
def kill_one(self):
global _nclients
_nclients -= 1
if _nclients == 0:
reactor.stop()
print ("done",_spawn_counter)
self.stop()
def spawn_more():
global _nclients,_client_gen
while _nclients < 50 and _client_gen:
try:
next(_client_gen)
_nclients += 1
except StopIteration:
_client_gen = []
break
def main():
#protocol = EchoClientDatagramProtocol()
#t = reactor.listenUDP(0, protocol)
global _nclients,_client_gen
_nclients = 10000 #upto 500
with open("sx.sx","r") as f:
ds = [line for line in f]
p = (EchoClientDatagramProtocol(iter(ds)) for _ in xrange(_nclients))
r = (reactor.listenUDP(0, i) for i in p)
_client_gen = r
_nclients = 0
spawn_more()
reactor.run();
if __name__ == '__main__':
main()
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
class Echo(DatagramProtocol):
def datagramReceived(self, data, (host, port)):
#print "received %r from %s:%d" % (data, host, port)
if host == "127.0.0.1":
self.transport.write("OK", (host, port))
reactor.listenUDP(62010, Echo())
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment