本文整理汇总了Python中autobahn.twisted.websocket.WampWebSocketServerFactory.protocol方法的典型用法代码示例。如果您正苦于以下问题:Python WampWebSocketServerFactory.protocol方法的具体用法?Python WampWebSocketServerFactory.protocol怎么用?Python WampWebSocketServerFactory.protocol使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autobahn.twisted.websocket.WampWebSocketServerFactory
的用法示例。
在下文中一共展示了WampWebSocketServerFactory.protocol方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_minimal
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
#.........这里部分代码省略.........
one_done = Deferred()
config.all_done.append(one_done)
def make_make(Klass, done):
def make(config):
c = Klass(config, done)
config.components.append(c)
return c
return make
## .. and set the session class on the factory
##
session_factory.session = make_make(C, one_done)
if self.transport == "websocket":
serializers = [JsonSerializer()]
## create a WAMP-over-WebSocket transport client factory
##
transport_factory = WampWebSocketClientFactory(session_factory, serializers = serializers, url = self.url, debug_wamp = self.debug)
if True:
def maker(Klass):
class TestClientProtocol(WampWebSocketClientProtocol):
def onOpen(self):
self.txcnt = 0
self.rxcnt = 0
WampWebSocketClientProtocol.onOpen(self)
def sendMessage(self, payload, isBinary):
self.txcnt += 1
print("> : {0:>3} : {1:<20} : {3}".format(self.txcnt, Klass.__name__, payload))
WampWebSocketClientProtocol.sendMessage(self, payload, isBinary)
def onMessage(self, payload, isBinary):
self.rxcnt += 1
print("< : {0:>3} : {1:<20} : {2}".format(self.rxcnt, Klass.__name__, payload))
WampWebSocketClientProtocol.onMessage(self, payload, isBinary)
return TestClientProtocol
transport_factory.protocol = maker(C)
else:
transport_factory.protocol = WampWebSocketClientProtocol
transport_factory.setProtocolOptions(failByDrop = False, openHandshakeTimeout = 0, closeHandshakeTimeout = 0)
elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:
## create a WAMP-over-RawSocket transport client factory
##
if self.transport == 'rawsocket-msgpack':
serializer = MsgPackSerializer()
elif self.transport == 'rawsocket-json':
serializer = JsonSerializer()
else:
raise Exception("should not arrive here")
transport_factory = WampRawSocketClientFactory(session_factory, serializer, debug = self.debug)
## start the client from an endpoint
##
cl = clientFromString(reactor, self.client)
clients_d.append(cl.connect(transport_factory))
clients.append(cl)
config.connected_clients = None
def client_connected(res):
config.connected_clients = [proto for success, proto in res if success]
DeferredList(clients_d).addCallback(client_connected)
d = DeferredList(config.all_done, consumeErrors = True)
#d = config.components[1]._done
def done(_):
log.flush()
log.close()
if config.port:
config.port.stopListening()
if config.connected_clients:
for proto in config.connected_clients:
proto.transport.abortConnection()
print("Log length: {0}".format(len(config.dlog)))
print(config.dlog)
#from twisted.internet import reactor
#reactor.callLater(1, reactor.stop)
def error(err):
print(err)
d.addCallbacks(done, error)
# d2 = Deferred()
return d
示例2: run
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
#.........这里部分代码省略.........
# we use an Autobahn utility to import the "best" available Twisted reactor
#
from autobahn.twisted.choosereactor import install_reactor
reactor = install_reactor(options.reactor)
from twisted.python.reflect import qual
log.info("Worker running under {python}-{reactor}",
python=platform.python_implementation(),
reactor=qual(reactor.__class__).split('.')[-1])
options.cbdir = os.path.abspath(options.cbdir)
os.chdir(options.cbdir)
# log.msg("Starting from node directory {}".format(options.cbdir))
from crossbar.worker.router import RouterWorkerSession
from crossbar.worker.container import ContainerWorkerSession
WORKER_TYPE_TO_CLASS = {
'router': RouterWorkerSession,
'container': ContainerWorkerSession
}
from autobahn.twisted.websocket import WampWebSocketServerProtocol
class WorkerServerProtocol(WampWebSocketServerProtocol):
def connectionLost(self, reason):
try:
# this log message is unlikely to reach the controller (unless
# only stdin/stdout pipes were lost, but not stderr)
log.warn("Connection to node controller lost.")
WampWebSocketServerProtocol.connectionLost(self, reason)
except:
pass
finally:
# losing the connection to the node controller is fatal:
# stop the reactor and exit with error
log.info("No more controller connection; shutting down.")
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
try:
reactor.stop()
except ReactorNotRunning:
pass
try:
# create a WAMP application session factory
#
from autobahn.twisted.wamp import ApplicationSessionFactory
from autobahn.wamp.types import ComponentConfig
session_config = ComponentConfig(realm=options.realm, extra=options)
session_factory = ApplicationSessionFactory(session_config)
session_factory.session = WORKER_TYPE_TO_CLASS[options.type]
# create a WAMP-over-WebSocket transport server factory
#
from autobahn.twisted.websocket import WampWebSocketServerFactory
transport_factory = WampWebSocketServerFactory(session_factory, "ws://localhost", debug=False, debug_wamp=False)
transport_factory.protocol = WorkerServerProtocol
transport_factory.setProtocolOptions(failByDrop=False)
# create a protocol instance and wire up to stdio
#
from twisted.python.runtime import platform as _platform
from twisted.internet import stdio
proto = transport_factory.buildProtocol(None)
if _platform.isWindows():
stdio.StandardIO(proto)
else:
stdio.StandardIO(proto, stdout=3)
# now start reactor loop
#
if False:
log.info("vmprof enabled.")
import os
import vmprof
PROFILE_FILE = 'vmprof_{}.dat'.format(os.getpid())
outfd = os.open(PROFILE_FILE, os.O_RDWR | os.O_CREAT | os.O_TRUNC)
vmprof.enable(outfd, period=0.01)
log.info("Entering event loop...")
reactor.run()
vmprof.disable()
else:
log.debug("Entering event loop...")
reactor.run()
except Exception as e:
log.info("Unhandled exception: {}".format(e))
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
else:
sys.exit(1)
示例3: run
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
#.........这里部分代码省略.........
# make sure logging to something else than stdio is setup _first_
#
from twisted.python import log
from crossbar.twisted.processutil import BareFormatFileLogObserver
flo = BareFormatFileLogObserver(sys.stderr)
log.startLoggingWithObserver(flo.emit)
try:
import setproctitle
except ImportError:
log.msg("Warning: could not set worker process title (setproctitle not installed)")
else:
# set process title if requested to
#
if options.title:
setproctitle.setproctitle(options.title)
else:
WORKER_TYPE_TO_TITLE = {
'router': 'crossbar-worker [router]',
'container': 'crossbar-worker [container]'
}
setproctitle.setproctitle(WORKER_TYPE_TO_TITLE[options.type].strip())
# we use an Autobahn utility to import the "best" available Twisted reactor
#
from autobahn.twisted.choosereactor import install_reactor
reactor = install_reactor(options.reactor)
from twisted.python.reflect import qual
log.msg("Running under {} using {} reactor".format(platform.python_implementation(), qual(reactor.__class__).split('.')[-1]))
options.cbdir = os.path.abspath(options.cbdir)
os.chdir(options.cbdir)
# log.msg("Starting from node directory {}".format(options.cbdir))
from crossbar.worker.router import RouterWorkerSession
from crossbar.worker.container import ContainerWorkerSession
WORKER_TYPE_TO_CLASS = {
'router': RouterWorkerSession,
'container': ContainerWorkerSession
}
from autobahn.twisted.websocket import WampWebSocketServerProtocol
class WorkerServerProtocol(WampWebSocketServerProtocol):
def connectionLost(self, reason):
try:
# this log message is unlikely to reach the controller (unless
# only stdin/stdout pipes were lost, but not stderr)
log.msg("Connection to node controller lost.")
WampWebSocketServerProtocol.connectionLost(self, reason)
except:
pass
finally:
# loosing the connection to the node controller is fatal:
# stop the reactor and exit with error
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
else:
sys.exit(1)
try:
# create a WAMP application session factory
#
from autobahn.twisted.wamp import ApplicationSessionFactory
from autobahn.wamp.types import ComponentConfig
session_config = ComponentConfig(realm=options.realm, extra=options)
session_factory = ApplicationSessionFactory(session_config)
session_factory.session = WORKER_TYPE_TO_CLASS[options.type]
# create a WAMP-over-WebSocket transport server factory
#
from autobahn.twisted.websocket import WampWebSocketServerFactory
transport_factory = WampWebSocketServerFactory(session_factory, "ws://localhost", debug=False, debug_wamp=False)
transport_factory.protocol = WorkerServerProtocol
transport_factory.setProtocolOptions(failByDrop=False)
# create a protocol instance and wire up to stdio
#
from twisted.internet import stdio
proto = transport_factory.buildProtocol(None)
stdio.StandardIO(proto)
# now start reactor loop
#
log.msg("Entering event loop ..")
reactor.run()
except Exception as e:
log.msg("Unhandled exception: {}".format(e))
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
else:
sys.exit(1)
示例4: RouterSessionFactory
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
##
from autobahn.twisted.wamp import RouterSessionFactory
session_factory = RouterSessionFactory(router_factory)
session_factory.session = MyRouterSession
# start an embedded application component ..
##
component_config = types.ComponentConfig(realm="realm1")
component_session = TimeService(component_config)
session_factory.add(component_session)
# create a WAMP-over-WebSocket transport server factory
##
from autobahn.twisted.websocket import WampWebSocketServerFactory
transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug=False, debug_wamp=args.debug)
transport_factory.protocol = ServerProtocol
transport_factory._cookies = {}
transport_factory.setProtocolOptions(failByDrop=False)
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.twisted.resource import WebSocketResource
# we serve static files under "/" ..
root = File(".")
# .. and our WebSocket server under "/ws"
resource = WebSocketResource(transport_factory)
root.putChild("ws", resource)
示例5: run
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
#.........这里部分代码省略.........
## make sure logging to something else than stdio is setup _first_
##
from crossbar.twisted.process import BareFormatFileLogObserver
flo = BareFormatFileLogObserver(sys.stderr)
log.startLoggingWithObserver(flo.emit)
## the worker's PID
##
pid = os.getpid()
try:
import setproctitle
except ImportError:
log.msg("Warning, could not set process title (setproctitle not installed)")
else:
## set process title if requested to
##
if options.name:
setproctitle.setproctitle(options.name)
else:
setproctitle.setproctitle("Crossbar.io Worker")
## Crossbar.io node directory
##
if hasattr(options, 'cbdir') and not options.cbdir:
if os.environ.has_key("CROSSBAR_DIR"):
options.cbdir = os.environ['CROSSBAR_DIR']
else:
options.cbdir = '.crossbar'
options.cbdir = os.path.abspath(options.cbdir)
log.msg("Starting from node directory {}.".format(options.cbdir))
## we use an Autobahn utility to import the "best" available Twisted reactor
##
from autobahn.twisted.choosereactor import install_reactor
reactor = install_reactor(options.reactor)
from twisted.python.reflect import qual
log.msg("Running on {} reactor.".format(qual(reactor.__class__).split('.')[-1]))
from autobahn.twisted.websocket import WampWebSocketServerProtocol
class WorkerServerProtocol(WampWebSocketServerProtocol):
def connectionLost(self, reason):
try:
log.msg("Connection to node controller lost.")
WampWebSocketServerProtocol.connectionLost(self, reason)
except:
pass
finally:
## loosing the connection to the node controller (the pipes) is fatal.
## stop the reactor and exit with error
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
else:
sys.exit(1)
try:
## create a WAMP application session factory
##
from autobahn.twisted.wamp import ApplicationSessionFactory
session_factory = ApplicationSessionFactory()
session_factory.options = options
session_factory.session = WorkerProcess
## create a WAMP-over-WebSocket transport server factory
##
from autobahn.twisted.websocket import WampWebSocketServerFactory
transport_factory = WampWebSocketServerFactory(session_factory, "ws://localhost", debug = False)
transport_factory.protocol = WorkerServerProtocol
transport_factory.setProtocolOptions(failByDrop = False)
## create a protocol instance and wire up to stdio
##
from twisted.internet import stdio
proto = transport_factory.buildProtocol(None)
stdio.StandardIO(proto)
## now start reactor loop
##
log.msg("Entering event loop ..")
#reactor.callLater(4, reactor.stop)
reactor.run()
except Exception as e:
log.msg("Unhandled exception - {}".format(e))
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
else:
sys.exit(1)
示例6: sendMessage
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
self.txcnt = 0
self.rxcnt = 0
WampWebSocketClientProtocol.onOpen(self)
def sendMessage(self, bytes, isBinary):
self.txcnt += 1
print("> : {:>3} : {:<20} : {}".format(self.txcnt, Klass.__name__, bytes))
WampWebSocketClientProtocol.sendMessage(self, bytes, isBinary)
def onMessage(self, bytes, isBinary):
self.rxcnt += 1
print("< : {:>3} : {:<20} : {}".format(self.rxcnt, Klass.__name__, bytes))
WampWebSocketClientProtocol.onMessage(self, bytes, isBinary)
return TestClientProtocol
transport_factory.protocol = maker(C)
else:
transport_factory.protocol = WampWebSocketClientProtocol
transport_factory.setProtocolOptions(failByDrop = False)
elif args.transport in ['rawsocket-json', 'rawsocket-msgpack']:
## create a WAMP-over-RawSocket transport client factory
##
if args.transport == 'rawsocket-msgpack':
from autobahn.wamp.serializer import MsgPackSerializer
serializer = MsgPackSerializer()
elif args.transport == 'rawsocket-json':
from autobahn.wamp.serializer import JsonSerializer
serializer = JsonSerializer()
示例7: _run_command_exec_worker
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
#.........这里部分代码省略.........
from twisted.internet.error import ConnectionDone
from autobahn.twisted.websocket import WampWebSocketServerProtocol
class WorkerServerProtocol(WampWebSocketServerProtocol):
def connectionLost(self, reason):
# the behavior here differs slightly whether we're shutting down orderly
# or shutting down because of "issues"
if isinstance(reason.value, ConnectionDone):
was_clean = True
else:
was_clean = False
try:
# this log message is unlikely to reach the controller (unless
# only stdin/stdout pipes were lost, but not stderr)
if was_clean:
log.info("Connection to node controller closed cleanly")
else:
log.warn("Connection to node controller lost: {reason}", reason=reason)
# give the WAMP transport a change to do it's thing
WampWebSocketServerProtocol.connectionLost(self, reason)
except:
# we're in the process of shutting down .. so ignore ..
pass
finally:
# after the connection to the node controller is gone,
# the worker is "orphane", and should exit
# determine process exit code
if was_clean:
exit_code = 0
else:
exit_code = 1
# exit the whole worker process when the reactor has stopped
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, exit_code)
# stop the reactor
try:
reactor.stop()
except ReactorNotRunning:
pass
try:
# define a WAMP application session factory
#
from autobahn.wamp.types import ComponentConfig
def make_session():
session_config = ComponentConfig(realm=options.realm, extra=options)
session = klass(config=session_config, reactor=reactor, personality=Personality)
return session
# create a WAMP-over-WebSocket transport server factory
#
from autobahn.twisted.websocket import WampWebSocketServerFactory
transport_factory = WampWebSocketServerFactory(make_session, u'ws://localhost')
transport_factory.protocol = WorkerServerProtocol
transport_factory.setProtocolOptions(failByDrop=False)
# create a protocol instance and wire up to stdio
#
from twisted.python.runtime import platform as _platform
from twisted.internet import stdio
proto = transport_factory.buildProtocol(None)
if _platform.isWindows():
stdio.StandardIO(proto)
else:
stdio.StandardIO(proto, stdout=3)
# now start reactor loop
#
if False:
log.info("vmprof enabled.")
import os
import vmprof
PROFILE_FILE = 'vmprof_{}.dat'.format(os.getpid())
outfd = os.open(PROFILE_FILE, os.O_RDWR | os.O_CREAT | os.O_TRUNC)
vmprof.enable(outfd, period=0.01)
log.info(hl('Entering event reactor ...', color='cyan', bold=True))
reactor.run()
vmprof.disable()
else:
log.info(hl('Entering event reactor ...', color='cyan', bold=True))
reactor.run()
except Exception as e:
log.info("Unhandled exception: {e}", e=e)
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
else:
sys.exit(1)
示例8: run
# 需要导入模块: from autobahn.twisted.websocket import WampWebSocketServerFactory [as 别名]
# 或者: from autobahn.twisted.websocket.WampWebSocketServerFactory import protocol [as 别名]
#.........这里部分代码省略.........
from crossbar._logging import Logger, make_JSON_observer
log = Logger()
_stderr = sys.stderr
flo = make_JSON_observer(_stderr)
globalLogBeginner.beginLoggingTo([flo])
try:
import setproctitle
except ImportError:
log.info("Warning: could not set worker process title (setproctitle not installed)")
else:
# set process title if requested to
#
if options.title:
setproctitle.setproctitle(options.title)
else:
WORKER_TYPE_TO_TITLE = {
'router': 'crossbar-worker [router]',
'container': 'crossbar-worker [container]'
}
setproctitle.setproctitle(WORKER_TYPE_TO_TITLE[options.type].strip())
# we use an Autobahn utility to import the "best" available Twisted reactor
#
from autobahn.twisted.choosereactor import install_reactor
reactor = install_reactor(options.reactor)
from twisted.python.reflect import qual
log.info("Running under {python} using {reactor} reactor",
python=platform.python_implementation(),
reactor=qual(reactor.__class__).split('.')[-1])
options.cbdir = os.path.abspath(options.cbdir)
os.chdir(options.cbdir)
# log.msg("Starting from node directory {}".format(options.cbdir))
from crossbar.worker.router import RouterWorkerSession
from crossbar.worker.container import ContainerWorkerSession
WORKER_TYPE_TO_CLASS = {
'router': RouterWorkerSession,
'container': ContainerWorkerSession
}
from autobahn.twisted.websocket import WampWebSocketServerProtocol
class WorkerServerProtocol(WampWebSocketServerProtocol):
def connectionLost(self, reason):
try:
# this log message is unlikely to reach the controller (unless
# only stdin/stdout pipes were lost, but not stderr)
log.warn("Connection to node controller lost.")
WampWebSocketServerProtocol.connectionLost(self, reason)
except:
pass
finally:
# loosing the connection to the node controller is fatal:
# stop the reactor and exit with error
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
# if the reactor *isn't* running, we're already shutting down
try:
# create a WAMP application session factory
#
from autobahn.twisted.wamp import ApplicationSessionFactory
from autobahn.wamp.types import ComponentConfig
session_config = ComponentConfig(realm=options.realm, extra=options)
session_factory = ApplicationSessionFactory(session_config)
session_factory.session = WORKER_TYPE_TO_CLASS[options.type]
# create a WAMP-over-WebSocket transport server factory
#
from autobahn.twisted.websocket import WampWebSocketServerFactory
transport_factory = WampWebSocketServerFactory(session_factory, "ws://localhost", debug=False, debug_wamp=False)
transport_factory.protocol = WorkerServerProtocol
transport_factory.setProtocolOptions(failByDrop=False)
# create a protocol instance and wire up to stdio
#
from twisted.internet import stdio
proto = transport_factory.buildProtocol(None)
stdio.StandardIO(proto)
# now start reactor loop
#
log.info("Entering event loop...")
reactor.run()
except Exception as e:
log.info("Unhandled exception: {}".format(e))
if reactor.running:
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, 1)
reactor.stop()
else:
sys.exit(1)