def startService(self): Service.startService(self) if self.__ws_port_obj is not None: raise Exception('Already started') self.__ws_port_obj = strports.listen(self.__ws_port, self.__ws_protocol) self.__http_port_obj = strports.listen(self.__http_port, self.__site)
def listen(config, top, noteDirty): rootCap = config['rootCap'] strports.listen(config['wsPort'], txws.WebSocketFactory(OurStreamFactory(top, rootCap))) # Roots of resource trees # - appRoot is everything stateful/authority-bearing # - serverRoot is the HTTP '/' and static resources are placed there serverRoot = _make_static(staticResourcePath) if rootCap is None: appRoot = serverRoot visitPath = '/' else: serverRoot = _make_static(staticResourcePath) appRoot = resource.Resource() serverRoot.putChild(rootCap, appRoot) visitPath = '/' + urllib.quote(rootCap, safe='') + '/' # UI entry point appRoot.putChild('', _make_static(os.path.join(_templatePath, 'index.html'))) # Exported radio control objects appRoot.putChild('radio', BlockResource(top, noteDirty, notDeletable)) # Frequency DB appRoot.putChild('dbs', shinysdr.db.DatabasesResource(config['databasesDir'])) # temporary stub till we have a proper writability/target policy appRoot.putChild('wdb', shinysdr.db.DatabaseResource([])) # Construct explicit resources for merge. test = _reify(serverRoot, 'test') jasmine = _reify(test, 'jasmine') for name in ['jasmine.css', 'jasmine.js', 'jasmine-html.js']: jasmine.putChild(name, static.File(os.path.join( os.path.dirname(__file__), 'deps/jasmine/lib/jasmine-core/', name))) client = _reify(serverRoot, 'client') client.putChild('openlayers', static.File(os.path.join( os.path.dirname(__file__), 'deps/openlayers'))) client.putChild('require.js', static.File(os.path.join( os.path.dirname(__file__), 'deps/require.js'))) # Plugin resources loadList = [] pluginResources = resource.Resource() client.putChild('plugins', pluginResources) for resourceDef in getPlugins(IClientResourceDef, shinysdr.plugins): pluginResources.putChild(resourceDef.key, resourceDef.resource) if resourceDef.loadURL is not None: # TODO constrain value loadList.append('/client/plugins/' + urllib.quote(resourceDef.key, safe='') + '/' + resourceDef.loadURL) # Client plugin list client.putChild('plugin-index.json', static.Data(json.dumps(loadList), 'application/json')) strports.listen(config['httpPort'], server.Site(serverRoot)) return _strport_to_url(config['httpPort'], path=visitPath)
def main(): arguments = parser.parse_args() if arguments.log: log.startLogging(open(arguments.log, 'w')) else: log.startLogging(sys.stderr) server = Server(base_path=arguments.directory) strports.listen(arguments.listen, txws.WebSocketFactory(SSWSFactory(server))) reactor.run()
def setup(self): self.channel_map = CONFIG['web']['channel_map'] self.history = dict((k, RelayHistory(CONFIG['web']['history_size'], CONFIG['web']['history_mode'])) for k in self.channel_map.values()) self.redis_factory = RedisFactory(self, list(v for v in self.channel_map.values())) self._web_factory = WebFactory(self, self.channel_map) self.ws_factory = WebSocketFactory(self._web_factory) reactor.connectTCP(CONFIG['redis_host'], CONFIG['redis_port'], self.redis_factory) listen(CONFIG['web']['host'], self.ws_factory)
def init(port=None): global _WebSocketListener global _AllAPIMethods global _APILogFileEnabled _APILogFileEnabled = settings.config.conf().getBool('logs/api-enabled') if _WebSocketListener is not None: lg.warn('_WebSocketListener already initialized') return if not port: port = settings.DefaultWebSocketPort() try: ws = BitDistWrappedWebSocketFactory(BitDustWebSocketFactory()) _WebSocketListener = listen("tcp:%d" % port, ws) except: lg.exc() return _AllAPIMethods = set(dir(api)) _AllAPIMethods.difference_update([ # TODO: keep that list up to date when changing the api 'on_api_result_prepared', 'Deferred', 'ERROR', 'Failure', 'OK', 'RESULT', '_Debug', '_DebugLevel', 'strng', 'sys', 'time', 'gc', 'map', 'os', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'absolute_import', 'driver', 'filemanager', 'jsn', 'lg', 'event_listen', 'message_receive', 'process_debug', ]) if _Debug: lg.out(_DebugLevel, 'api_web_socket.init _WebSocketListener=%r with %d methods' % ( _WebSocketListener, len(_AllAPIMethods))) read_api_secret() events.add_subscriber(on_event, event_id='*')
def __init__(self, portstr): self.portstr = portstr self.users = {} # there's lots of stuff to set up for a PB connection! self.portal = portal.Portal(self) self.portal.registerChecker(self) self.serverFactory = pb.PBServerFactory(self.portal) self.serverFactory.unsafeTracebacks = True self.port = strports.listen(portstr, self.serverFactory)
def startService(self): assert not self.port self.port = strports.listen(self.portstr, self.serverFactory) return service.AsyncService.startService(self)
def startService(self): self.__port_obj = strports.listen(self.__endpoint, _DspserverFactory(self.__top))
log.msg("Closing connection: %r (%d)" % (text, reason)) # Close the connection. self.close() class WSFactory(WebSocketFactory): protocol = Wrapper class EchoProtocol(Protocol): def dataReceived(self, data): print 'echo data receive', data def makeConnection(self, transport): Protocol.makeConnection(self, transport) self.ping() def ping(self): self.transport.write(PING_CODE) reactor.callLater(3, self.ping) class EchoFactory(Factory): protocol = EchoProtocol port = listen("tcp:5600", WSFactory(EchoFactory())) reactor.run()
def listen(config, top, noteDirty): rootCap = config['rootCap'] ws_port_obj = strports.listen(config['wsPort'], txws.WebSocketFactory(OurStreamFactory(top, rootCap))) # Roots of resource trees # - appRoot is everything stateful/authority-bearing # - serverRoot is the HTTP '/' and static resources are placed there serverRoot = _make_static(staticResourcePath) if rootCap is None: appRoot = serverRoot visitPath = '/' else: serverRoot = _make_static(staticResourcePath) appRoot = _SlashedResource() serverRoot.putChild(rootCap, appRoot) visitPath = '/' + urllib.quote(rootCap, safe='') + '/' # UI entry point appRoot.putChild('', _make_static(os.path.join(_templatePath, 'index.html'))) # Exported radio control objects appRoot.putChild('radio', BlockResource(top, noteDirty, notDeletable)) # Frequency DB appRoot.putChild('dbs', shinysdr.db.DatabasesResource(config['databasesDir'])) # temporary stub till we have a proper writability/target policy appRoot.putChild('wdb', shinysdr.db.DatabaseResource([])) # Construct explicit resources for merge. test = _reify(serverRoot, 'test') jasmine = _reify(test, 'jasmine') for name in ['jasmine.css', 'jasmine.js', 'jasmine-html.js']: jasmine.putChild(name, static.File(os.path.join( os.path.dirname(__file__), 'deps/jasmine/lib/jasmine-core/', name))) client = _reify(serverRoot, 'client') client.putChild('openlayers', static.File(os.path.join( os.path.dirname(__file__), 'deps/openlayers'))) client.putChild('require.js', static.File(os.path.join( os.path.dirname(__file__), 'deps/require.js'))) # Plugin resources loadList = [] pluginResources = resource.Resource() client.putChild('plugins', pluginResources) for resourceDef in getPlugins(IClientResourceDef, shinysdr.plugins): pluginResources.putChild(resourceDef.key, resourceDef.resource) if resourceDef.loadURL is not None: # TODO constrain value loadList.append('/client/plugins/' + urllib.quote(resourceDef.key, safe='') + '/' + resourceDef.loadURL) # Client plugin list client.putChild('plugin-index.json', static.Data(json.dumps(loadList), 'application/json')) web_port_obj = strports.listen(config['httpPort'], server.Site(serverRoot)) port_num = web_port_obj.socket.getsockname()[1] # TODO touching implementation, report need for a better way (web_port_obj.port is 0 if specified port is 0, not actual port) url = _strport_to_url(config['httpPort'], socket_port=port_num, path=visitPath) def stop(): # TODO: Does Twisted already have something to bundle up a bunch of ports for shutdown? return defer.DeferredList([ web_port_obj.stopListening(), ws_port_obj.stopListening()]) return (stop, url)
class ProxyFactory(Factory): protocol = ProxyProtocol def main(): o = ServiceOptions() try: o.parseOptions() except usage.UsageError, msg: print "%s: %s" % (sys.argv[0], msg) print "%s: use --help for usage details" % (sys.argv[0],) raise SystemExit, 1 zf = ZmqFactory() sub = ZmqSubConnection(zf, ZmqEndpoint("connect", "tcp://%s" % o.opts['subsocket'])) sub.subscribe("") ws = listen("tcp:%s" % o.opts['websocket'], WebSocketFactory(ProxyFactory())) def forwardToWs(msg): for c in connections: c.transport.write(msg) sub.gotMessage = forwardToWs reactor.run() if __name__ == '__main__': main()
from twisted.python import log from sys import stdout log.startLogging(stdout) from twisted.internet.protocol import Protocol, Factory class EchoProtocol(Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(Factory): protocol = EchoProtocol from txws import WebSocketFactory from twisted.application.strports import listen port = listen("tcp:5600", WebSocketFactory(EchoFactory())) from twisted.internet import reactor reactor.run()
def startService(self): self.__port_obj = strports.listen( self.__endpoint, FactoryWithArgs.forProtocol(_DspserverProtocol, self.__top))
buf += struct.pack('x') buf += struct.pack('!H', 1) buf += struct.pack('H', x_pos) buf += struct.pack('!H', y_pos) buf += struct.pack('!H', img.size[0]) buf += struct.pack('!H', img.size[1]) buf += struct.pack('!i', 0) self.transport.write(buf) buf = img.tostring('raw', 'RGBX') print 'Image size:', len(buf) self.transport.write(buf) class RFBFactory(Factory): protocol = RFBProtocol txws.encoders = { "base64": b64encode, "binary, base64": b64encode, } txws.decoders = { "base64": b64decode, "binary, base64": b64decode, } port = listen("tcp:8080", txws.WebSocketFactory(RFBFactory())) reactor.run()
instance() else: import sys from twisted.python import log log.startLogging(sys.stdout) from twisted.application import strports from twisted.python import usage from xmpp_tester import XmppTestServerFactory from tests import startTests from twisted.internet import reactor exitcode = 0 def starter(f): d = startTests(f) def errback(x): print 'Test result:', x print 'Killing',fr os.kill(fr, 2) global exitcode exitcode = 1 if x else 0 reactor.stop() d.addCallbacks(errback, errback) factory = XmppTestServerFactory(starter) svc = strports.listen('tcp:9781:interface=127.0.0.1', factory) #reactor.callWhenRunning(startTests, reactor, factory) reactor.run() sys.exit(exitcode) #from bnw.scripts
def startService(self): self.__port_obj = strports.listen(self.__endpoint, FactoryWithArgs.forProtocol(_DspserverProtocol, self.__top))
def start_listening_port(self): return strports.listen(self.portstr, self.serverFactory)