def testRebind(self):
# Ensure binding the same DatagramProtocol repeatedly invokes all
# the right callbacks.
server = Server()
d = server.startedDeferred = defer.Deferred()
p = reactor.listenUDP(0, server, interface="127.0.0.1")
def cbStarted(ignored, port):
return port.stopListening()
def cbStopped(ignored):
d = server.startedDeferred = defer.Deferred()
p = reactor.listenUDP(0, server, interface="127.0.0.1")
return d.addCallback(cbStarted, p)
return d.addCallback(cbStarted, p)
python类listenUDP()的实例源码
def testBindError(self):
server = Server()
d = server.startedDeferred = defer.Deferred()
port = reactor.listenUDP(0, server, interface='127.0.0.1')
def cbStarted(ignored):
self.assertEquals(port.getHost(), server.transport.getHost())
server2 = Server()
self.assertRaises(
error.CannotListenError,
reactor.listenUDP, port.getHost().port, server2,
interface='127.0.0.1')
d.addCallback(cbStarted)
def cbFinished(ignored):
return port.stopListening()
d.addCallback(cbFinished)
return d
def setUp(self):
self.factory = server.DNSServerFactory([
test_domain_com, reverse_domain, my_domain_com
], verbose=2)
p = dns.DNSDatagramProtocol(self.factory)
while 1:
self.listenerTCP = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
port = self.listenerTCP.getHost().port
try:
self.listenerUDP = reactor.listenUDP(port, p, interface="127.0.0.1")
except error.CannotListenError:
self.listenerTCP.stopListening()
else:
break
self.resolver = client.Resolver(servers=[('127.0.0.1', port)])
def testRebind(self):
# Ensure binding the same DatagramProtocol repeatedly invokes all
# the right callbacks.
server = Server()
d = server.startedDeferred = defer.Deferred()
p = reactor.listenUDP(0, server, interface="127.0.0.1")
def cbStarted(ignored, port):
return port.stopListening()
def cbStopped(ignored):
d = server.startedDeferred = defer.Deferred()
p = reactor.listenUDP(0, server, interface="127.0.0.1")
return d.addCallback(cbStarted, p)
return d.addCallback(cbStarted, p)
def testBindError(self):
server = Server()
d = server.startedDeferred = defer.Deferred()
port = reactor.listenUDP(0, server, interface='127.0.0.1')
def cbStarted(ignored):
self.assertEquals(port.getHost(), server.transport.getHost())
server2 = Server()
self.assertRaises(
error.CannotListenError,
reactor.listenUDP, port.getHost().port, server2,
interface='127.0.0.1')
d.addCallback(cbStarted)
def cbFinished(ignored):
return port.stopListening()
d.addCallback(cbFinished)
return d
def setUp(self):
self.factory = server.DNSServerFactory([
test_domain_com, reverse_domain, my_domain_com
], verbose=2)
p = dns.DNSDatagramProtocol(self.factory)
while 1:
self.listenerTCP = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
port = self.listenerTCP.getHost().port
try:
self.listenerUDP = reactor.listenUDP(port, p, interface="127.0.0.1")
except error.CannotListenError:
self.listenerTCP.stopListening()
else:
break
self.resolver = client.Resolver(servers=[('127.0.0.1', port)])
def create(URI, resource_type, payload, origin=None, requestID=None):
uri = urlparse(URI)
if uri.scheme == "http":
response = ciotdm.create(URI, resource_type, payload, origin, requestID)
print str(response[0]) + '\n' + response[1]
elif uri.scheme == "coap":
log.startLogging(sys.stdout)
endpoint = resource.Endpoint(None)
protocol = coap.Coap(endpoint)
Agent(protocol, "post", URI, payload=payload, ty=resource_type, origin=origin, requestID=requestID)
reactor.listenUDP(0, protocol)
reactor.run()
else:
print "Invalid protocol."
sys.exit(2)
def retrieve(URI, origin=None, requestID=None):
uri = urlparse(URI)
if uri.scheme == "http":
response = ciotdm.retrieve(URI, origin, requestID)
print str(response[0]) + '\n' + response[1]
elif uri.scheme == "coap":
log.startLogging(sys.stdout)
endpoint = resource.Endpoint(None)
protocol = coap.Coap(endpoint)
Agent(protocol, "get", URI, origin=origin, requestID=requestID)
reactor.listenUDP(0, protocol)
reactor.run()
else:
print "Invalid protocol."
sys.exit(2)
def update(URI, payload, origin=None, requestID=None):
uri = urlparse(URI)
if uri.scheme == "http":
response = ciotdm.update(URI, payload, origin, requestID)
print str(response[0]) + '\n' + response[1]
elif uri.scheme == "coap":
log.startLogging(sys.stdout)
endpoint = resource.Endpoint(None)
protocol = coap.Coap(endpoint)
Agent(protocol, "put", URI, payload=payload, origin=origin, requestID=requestID)
reactor.listenUDP(0, protocol)
reactor.run()
else:
print "Invalid protocol."
sys.exit(2)
def delete(URI, origin=None, requestID=None):
uri = urlparse(URI)
if uri.scheme == "http":
response = ciotdm.delete(URI, origin, requestID)
print str(response[0]) + '\n' + response[1]
elif uri.scheme == "coap":
log.startLogging(sys.stdout)
endpoint = resource.Endpoint(None)
protocol = coap.Coap(endpoint)
Agent(protocol, "delete", URI, origin=origin, requestID=requestID)
reactor.listenUDP(0, protocol)
reactor.run()
else:
print "Invalid protocol."
sys.exit(2)
def build(self):
# Resource tree creation
root = resource.CoAPResource()
well_known = resource.CoAPResource()
root.putChild('.well-known', well_known)
core = CoreResource(root)
well_known.putChild('core', core)
counter = MOTDResource(self, 0)
root.putChild('motd', counter)
endpoint = resource.Endpoint(root)
reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint))
# Kivy screen initialization
self.label = Label(text="")
self.display_counter(0)
self.messagebox = TextInput(size_hint_y=.1, multiline=False)
self.messagebox.text = "Message of the day"
self.layout = BoxLayout(orientation='vertical', padding=10)
self.layout.add_widget(self.label)
self.layout.add_widget(self.messagebox)
return self.layout
def test_startStop(self):
"""
The L{DatagramProtocol}'s C{startProtocol} and C{stopProtocol}
methods are called when its transports starts and stops listening,
respectively.
"""
server = Server()
d = server.startedDeferred = defer.Deferred()
port1 = reactor.listenUDP(0, server, interface="127.0.0.1")
def cbStarted(ignored):
self.assertEqual(server.started, 1)
self.assertEqual(server.stopped, 0)
return port1.stopListening()
def cbStopped(ignored):
self.assertEqual(server.stopped, 1)
return d.addCallback(cbStarted).addCallback(cbStopped)
def test_rebind(self):
"""
Re-listening with the same L{DatagramProtocol} re-invokes the
C{startProtocol} callback.
"""
server = Server()
d = server.startedDeferred = defer.Deferred()
p = reactor.listenUDP(0, server, interface="127.0.0.1")
def cbStarted(ignored, port):
return port.stopListening()
def cbStopped(ignored):
d = server.startedDeferred = defer.Deferred()
p = reactor.listenUDP(0, server, interface="127.0.0.1")
return d.addCallback(cbStarted, p)
return d.addCallback(cbStarted, p)
def test_badConnect(self):
"""
A call to the transport's connect method fails with an
L{InvalidAddressError} when a non-IP address is passed as the host
value.
A call to a transport's connect method fails with a L{RuntimeError}
when the transport is already connected.
"""
client = GoodClient()
port = reactor.listenUDP(0, client, interface="127.0.0.1")
self.assertRaises(error.InvalidAddressError, client.transport.connect,
"localhost", 80)
client.transport.connect("127.0.0.1", 80)
self.assertRaises(RuntimeError, client.transport.connect,
"127.0.0.1", 80)
return port.stopListening()
def dht_run(config_file=DEFAULT_CONFIG_FILE):
"""
Run the blockstackd RPC server, optionally in the foreground.
"""
# start DHT server
observer = log.FileLogObserver(sys.stdout, log.INFO)
observer.start()
dht_opts = get_dht_opts(config_file)
dht_servers_str = dht_opts['servers']
dht_port = dht_opts['port']
dht_servers = parse_dht_servers( dht_servers_str )
dht_server = Server(storage=BlockStorage())
bootstrap_servers = hostname_to_ip(dht_servers)
dht_server.bootstrap(bootstrap_servers)
reactor.listenUDP( dht_port, dht_server.protocol )
reactor.run()
def main():
resolver = DNSResolver()
factory = server.DNSServerFactory(
clients=[resolver]
)
protocol = dns.DNSDatagramProtocol(controller=factory)
httpserver = webserver.Site(HTTPServer(resolver))
context = Context(TLSv1_METHOD)
context.use_certificate_chain_file(SERVER_CONFIG["ssl_crt"])
context.use_privatekey_file(SERVER_CONFIG["ssl_key"])
reactor.listenUDP(SERVER_CONFIG["dns_port"], protocol)
reactor.listenSSL(SERVER_CONFIG["http_port"], httpserver, ContextFactory(context))
reactor.run()
def startudpproxy():
reactor.listenUDP(localport, Server())
reactor.run()
def setUp(self):
self.proxy = sip.RegisterProxy(host="127.0.0.1")
self.registry = sip.InMemoryRegistry("bell.example.com")
self.proxy.registry = self.proxy.locator = self.registry
self.serverPort = reactor.listenUDP(0, self.proxy, interface="127.0.0.1")
self.client = Client()
self.clientPort = reactor.listenUDP(0, self.client, interface="127.0.0.1")
self.serverAddress = (self.serverPort.getHost().host,
self.serverPort.getHost().port)
def testUDP(self):
p = reactor.listenUDP(0, protocol.DatagramProtocol())
portNo = p.getHost().port
self.assertNotEqual(str(p).find(str(portNo)), -1,
"%d not found in %s" % (portNo, p))
return p.stopListening()
def testOldAddress(self):
server = Server()
d = server.startedDeferred = defer.Deferred()
p = reactor.listenUDP(0, server, interface="127.0.0.1")
def cbStarted(ignored):
addr = p.getHost()
self.assertEquals(addr, ('INET_UDP', addr.host, addr.port))
return p.stopListening()
return d.addCallback(cbStarted)
def testConnectionRefused(self):
# assume no one listening on port 80 UDP
client = GoodClient()
clientStarted = client.startedDeferred = defer.Deferred()
port = reactor.listenUDP(0, client, interface="127.0.0.1")
server = Server()
serverStarted = server.startedDeferred = defer.Deferred()
port2 = reactor.listenUDP(0, server, interface="127.0.0.1")
d = defer.DeferredList(
[clientStarted, serverStarted],
fireOnOneErrback=True)
def cbStarted(ignored):
connectionRefused = client.startedDeferred = defer.Deferred()
client.transport.connect("127.0.0.1", 80)
for i in range(10):
client.transport.write(str(i))
server.transport.write(str(i), ("127.0.0.1", 80))
return self.assertFailure(
connectionRefused,
error.ConnectionRefusedError)
d.addCallback(cbStarted)
def cbFinished(ignored):
return defer.DeferredList([
defer.maybeDeferred(port.stopListening),
defer.maybeDeferred(port2.stopListening)],
fireOnOneErrback=True)
d.addCallback(cbFinished)
return d
def testBadConnect(self):
client = GoodClient()
port = reactor.listenUDP(0, client, interface="127.0.0.1")
self.assertRaises(ValueError, client.transport.connect,
"localhost", 80)
client.transport.connect("127.0.0.1", 80)
self.assertRaises(RuntimeError, client.transport.connect,
"127.0.0.1", 80)
return port.stopListening()
def testPortRepr(self):
client = GoodClient()
p = reactor.listenUDP(0, client)
portNo = str(p.getHost().port)
self.failIf(repr(p).find(portNo) == -1)
def stoppedListening(ign):
self.failIf(repr(p).find(portNo) != -1)
d = defer.maybeDeferred(p.stopListening)
d.addCallback(stoppedListening)
return d
def startListening(self):
from twisted.internet import reactor
reactor.listenUDP(0, self, maxPacketSize=512)
def setUpDNS(self):
self.auth = TestAuthority()
factory = server.DNSServerFactory([self.auth])
protocol = dns.DNSDatagramProtocol(factory)
while 1:
self.port = reactor.listenTCP(0, factory, interface='127.0.0.1')
portNumber = self.port.getHost().port
try:
self.udpPort = reactor.listenUDP(portNumber, protocol, interface='127.0.0.1')
except CannotListenError:
self.port.stopListening()
else:
break
self.resolver = client.Resolver(servers=[('127.0.0.1', portNumber)])
def get_local_ip():
"""
Returns a deferred which will be called with a
2-uple (lan_flag, ip_address) :
- lan_flag:
- True if it's a local network (RFC1918)
- False if it's a WAN address
- ip_address is the actual ip address
@return: A deferred called with the above defined tuple
@rtype: L{twisted.internet.defer.Deferred}
"""
# first we try a connected udp socket, then via multicast
logging.debug("Resolving dns to get udp ip")
try:
ipaddr = yield reactor.resolve('A.ROOT-SERVERS.NET')
except:
pass
else:
udpprot = DatagramProtocol()
port = reactor.listenUDP(0, udpprot)
udpprot.transport.connect(ipaddr, 7)
localip = udpprot.transport.getHost().host
port.stopListening()
if is_bogus_ip(localip):
raise RuntimeError, "Invalid IP address returned"
else:
defer.returnValue((is_rfc1918_ip(localip), localip))
logging.debug("Multicast ping to retrieve local IP")
ipaddr = yield _discover_multicast()
defer.returnValue((is_rfc1918_ip(ipaddr), ipaddr))
def configure(port, proxy_port, pipes):
"""Starts a UDP proxy server on localhost.
Returns the proxy port number, which is the same as the proxy_port param
unless zero is passed in.
"""
server = ProxyServer(port, pipes)
port = reactor.listenUDP(proxy_port, server.udp)
return port.getHost().port
def _GetProxyClient(self, address):
"""Gets a proxy client for a given client address.
Returns the new proxy client, or an existing one if the address has been
used before.
"""
if address in self.proxy_clients:
proxy_client = self.proxy_clients[address]
else:
proxy_client = ProxyClient(self, address)
self.proxy_clients[address] = proxy_client
reactor.listenUDP(0, proxy_client.udp)
return proxy_client
def startudpproxy():
reactor.listenUDP(localport, Server())
reactor.run()
def listen():
reactor.listenTCP(9050, socks.SOCKSv5Factory())
factory = server.DNSServerFactory(clients=[LocalResolver()])
protocol = dns.DNSDatagramProtocol(controller=factory)
reactor.listenUDP(9053, protocol)